2014-09-30 50 views
2

我在写注释处理器。我怎样才能得到一个数组的类型?在Java注释处理器中获取数组的类型

@MyAnnotation 
int[] iArray; 


@MyAnnotation 
boolean[] bArray; 


@MyAnnotation 
FooClass[] fooArray; 

据我知道我可以检查它是否是这样的一个数组:

if (element.asType().getKind() == TypeKind.ARRAY) { 
    // it's an array 
    // How to check if its an array of boolean or an array integer, etc.? 
} 

如何获取数组的类型?

基本上我遍历与@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.? 
    } 
} 
+0

Element是什么类型的? – 2014-09-30 15:16:41

+0

元素是'VariableElement' – sockeqwe 2014-09-30 15:17:21

+0

做数组中的第一个元素的一个instaterof ... – StackFlowed 2014-09-30 15:28:22

回答

4

一旦你知道它是一个数组类型,你可以将其类型转换为ArrayType

ArrayType asArrayType = (ArrayType) element.asType(); 

ArrayType具有getComponentType()方法,所以

asArrayType.getComponentType(); 

获取组件类型。

然后,您可以重复该过程以获取组件类型的TypeKind

+0

谢谢!那正是我所期待的 – sockeqwe 2014-09-30 15:34:30