Mar*_*iot 24 java eclipse annotations
我正在尝试创建一个新的注释,我将在其中进行一些运行时布线,但是,由于多种原因,我想在编译时验证我的布线是否会成功进行一些基本检查.
假设我创建了一个新注释:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomAnnotation{
}
Run Code Online (Sandbox Code Playgroud)
现在我想在编译时进行某种验证,比如检查CustomAnnotation
注释是否属于特定类型的字段:ParticularType
.我在Java 6工作,所以我创建了一个AbstractProcessor
:
@SupportedAnnotationTypes("com.example.CustomAnnotation")
public class CompileTimeAnnotationProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(CustomAnnotation.class);
for(Element e : elements){
if(!e.getClass().equals(ParticularType.class)){
processingEnv.getMessager().printMessage(Kind.ERROR,
"@CustomAnnotation annotated fields must be of type ParticularType");
}
}
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,根据我发现的一些说明,我创建了一个文件夹META-INF/services
并创建了一个javax.annotation.processing.Processor
包含内容的文件:
com.example.CompileTimeAnnotationProcessor
Run Code Online (Sandbox Code Playgroud)
然后,我将项目导出为jar.
在另一个项目中,我构建了一个简单的测试类:
public class TestClass {
@CustomAnnotation
private String bar; // not `ParticularType`
}
Run Code Online (Sandbox Code Playgroud)
我按如下方式配置了Eclipse项目属性:
我点击了"apply",Eclipse提示重建项目,我点击了 - 但是没有错误,尽管有注释处理器.
我哪里做错了?
我用javac
as来运行它
javac -classpath "..\bin;path\to\tools.jar" -processorpath ..\bin -processor com.example.CompileTimeAnnotationProcessor com\test\TestClass.java
Run Code Online (Sandbox Code Playgroud)
与输出
@CustomAnnotation带注释的字段必须是ParticularType类型
Mar*_*iot 17
要在编辑器中显示Element
错误,需要在printMessage
函数中标记导致错误的错误.对于上面的示例,这意味着编译时检查应使用:
processingEnv.getMessager().printMessage(Kind.ERROR,
"@CustomAnnotation annotated fields must be of type ParticularType",
e); // note we explicitly pass the element "e" as the location of the error
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12849 次 |
最近记录: |