项目性质允许插件将项目标记为特定类型的项目。例如,“Java 开发工具”(JDT)使用“Java 性质”来将特定于 Java 的行为添加到项目中。项目性质由插件定义,并通常当用户执行一些由插件定义的操作时按项目进行添加或除去。
一个项目可以有多个性质。但是,当您定义项目性质时,您可以定义性质的特殊约束:
要实现您自己的性质,需要定义扩展,并提供用来实现 IProjectNature 的类。
org.eclipse.core.resources.natures 扩展点用来添加项目性质定义。以下标记为虚拟的 com.example.natures 插件添加性质。
<extension point="org.eclipse.core.resources.natures" id="myNature" name="My Nature"> <runtime> <run class="com.example.natures.MyNature"> </run> </runtime> </extension>
在扩展中标识的类必须实现平台接口 IProjectNature。此类实现特定于插件的行为,以便在配置性质时将特定于性质的信息与项目相关联。
public class MyNature implements IProjectNature { private IProject project; public void configure() throws CoreException { // Add nature-specific information // for the project, such as adding a builder // to a project's build spec. } public void deconfigure() throws CoreException { // Remove the nature-specific information here. } public IProject getProject() { return project; } public void setProject(IProject value) { project = value; } }
configure() 和 deconfigure() 方法是在项目中添加和除去性质时由平台发送的。可以实现 configure() 方法,以便按在构建器中讨论的那样来将构建器添加到项目中。
定义性质不足以将其与项目关联。您必须通过更新项目描述以包括您的性质来指定项目的性质。这通常在用户使用指定性质的专门新项目向导来创建新项目时发生。以下 snippet 显示如何指定给定项目的新性质。
try { IProjectDescription description = project.getDescription(); String[] natures = description.getNatureIds(); String[] newNatures = new String[natures.length + 1]; System.arraycopy(natures, 0, newNatures, 0, natures.length); newNatures[natures.length] = "com.example.natures.myNature"; description.setNatureIds(newNatures); project.setDescription(description, null); } catch (CoreException e) { // Something went wrong }
在您将项目描述设置到项目中之前,实际上未对项目指定(和配置)性质。另外注意:用于性质的标识是性质扩展的全限定名(插件标识 + 扩展标识)。
若定义了带约束的性质,则可以使用工作区 API 来验证新性质。例如,假定定义了带先决条件的性质:
<extension point="org.eclipse.core.resources.natures" id="myOtherNature" name="My Other Nature"> <runtime> <run class="com.example.natures.MyOtherNature"> </run> </runtime> <requires-nature id="com.example.natures.myNature"/> </extension>
除非存在项目的第一个性质,否则新性质无效。取决于插件的设计,您可能要检查是否安装了先决条件性质,或您可能要自己添加先决条件性质。无论用哪一种方法,您都可以使用工作区 API 来检查提议的项目性质组合的有效性。
try { IProjectDescription description = project.getDescription(); String[] natures = description.getNatureIds(); String[] newNatures = new String[natures.length + 1]; System.arraycopy(natures, 0, newNatures, 0, natures.length); newNatures[natures.length] = "com.example.natures.myOtherNature"; IStatus status = workspace.validateNatureSet(natures); // check the status and decide what to do if (status.getCode() == IStatus.OK) { description.setNatureIds(newNatures); project.setDescription(description, null); } else { // raise a user error ... } } catch (CoreException e) { // Something went wrong }
除了通过性质的标识处理性质外,您还可以获取描述符(IProjectNatureDescriptor) 它描述一个性质、其约束及其标号。您可以查询特定性质以得到其描述符,或从工作区得到描述符。以下 snippet 获得我们新性质的项目性质描述符:
IProjectNatureDescriptor descriptor = workspace.getNatureDescriptor("com.example.natures.myOtherNature");
您还可以获得所有已安装性质的描述符数组:
IProjectNatureDescriptor[] descriptors = workspace.getNatureDescriptors();