soc*_*qwe 2 java annotations annotation-processing
我正在写一个注释处理器.我怎样才能获得数组的类型?
@MyAnnotation
int[] iArray;
@MyAnnotation
boolean[] bArray;
@MyAnnotation
FooClass[] fooArray;
Run Code Online (Sandbox Code Playgroud)
据我所知,我可以检查它是否是这样的数组:
if (element.asType().getKind() == TypeKind.ARRAY) {
// it's an array
// How to check if its an array of boolean or an array integer, etc.?
}
Run Code Online (Sandbox Code Playgroud)
我如何获得数组的类型?
基本上我迭代所有注释的元素@MyAnnotation,我将根据数组的类型对数组做一些特殊的事情,类似于:
for (Element element : enviroment.getElementsAnnotatedWith(MyAnnotation.class)) {
if (element.getKind() != ElementKind.FIELD)
continue;
if (element.asType().getKind() == TypeKind.ARRAY) {
// it's an array
// How to distinguish between array of boolean or an array integer, etc.?
}
}
Run Code Online (Sandbox Code Playgroud)
一旦你知道它是一个数组类型,你可以将它的类型转换为ArrayType.
ArrayType asArrayType = (ArrayType) element.asType();
Run Code Online (Sandbox Code Playgroud)
ArrayType有一个getComponentType()方法,所以
asArrayType.getComponentType();
Run Code Online (Sandbox Code Playgroud)
获取组件类型.
然后,您可以重复该过程以获取组件类型TypeKind.