项目性质允许插件将项目标记为特定类型的项目。例如,“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 {
// 添加有关项目的特定于性质的信息
// 如将构建器添加至
// 项目的构建规范。
}
public void deconfigure() throws CoreException {
// 在此处除去特定于性质的信息。
}
public IProject getProject() {
return project;
}
public void setProject(IProject value) {
project = value;
}
}
configure() 和 deconfigure() 方法是在项目中添加和除去性质时由平台发送的。可以实现 configure() 方法,以便按在构建器中讨论的那样来将构建器添加到项目中。
一旦定义了性质并且实现了它的类,就必须为项目指定该性质。以下代码片段为给定的项目指定了新性质。
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) {
// 有些地方不对
}
用于性质的标识符是性质扩展的全限定名(插件标识加上扩展标识)。
一般是在创建性质时将性质添加到项目中的。通常,提供一个定制的新项目向导,以捕获关于项目的特殊信息,并为该向导指定该性质。