从TypeMirror获取数组的类类型

时间:2013-11-05 09:44:33

标签: java

我正在做Java APT并想要解析一个方法(ExecutableElement)。现在我需要方法的返回类型。我不知道如何获取类型,如果它是一个数组。

示例:String[] foobar()

我想获得String类型。

在ExecutableElement实例中,我可以将return-type作为TypeMirror的一个实例(使用getReturnType())。但如果它是一个数组,我就无法获得“真实类型”(在我的例子中:String)。

我试过了:

System.out.println("TEST: " + pReturnType.toString());
System.out.println("TEST2: " + pReturnType.getClass().getName());
System.out.println("TEST3: " + pReturnType.getClass().getEnclosingClass());
System.out.println("TEST4: " + pReturnType.getClass().getComponentType());
System.out.println("TEST5: " + pReturnType.getKind());

这给了我:

TEST: java.lang.String[]
TEST2: com.sun.tools.javac.code.Type$ArrayType
TEST3: class com.sun.tools.javac.code.Type
TEST4: null
TEST5: ARRAY

我想要一个java.lang.Class的实例,代表java.lang.String(在我的例子中)。

5 个答案:

答案 0 :(得分:4)

我知道这是一个老问题,但这里的所有答案都在考虑反射,而不是TypeMirror,它是注释处理api的一部分,而不是反射。

要从typeMirror获取组件类型,必须将其转换为ArrayType并调用方法ArrayType::getComponentType(),即

TypeMirror pReturnType = ...
if (pReturnType.getKind() == TypeKind.ARRAY) {
    return ((ArrayType)pReturnType).getComponentType();
} else {
  //this is not an array type..
}

答案 1 :(得分:1)

方法“getComponentType”工作正常:

public String[] getValues() {
    return null;
}

@Test
public void testIt() throws Exception {
    Method m = this.getClass().getMethod("getValues");
    if (m.getReturnType().isArray()) {
        System.out.println(m.getReturnType().getComponentType());
    }
}

输出为:class java.lang.String

答案 2 :(得分:1)

我解决了这个问题:

TypeMirror tm = fieldElement.asType();
    try {
        this.fieldType = Class.forName(tm.toString());
    } catch (ClassNotFoundException e) {
        throw new IllegalStateException("unsupported datatype: " + tm.toString());
    }

tm.toString()有例如value:" java.lang.String"

答案 3 :(得分:0)

这是你想要的

System.out.println(pReturnType.getClass().getSimpleName());

其打印字符串[]

但您想要字符串,您必须提供索引。

例如System.out.println(pReturnType[i].getClass().getSimpleName());

答案 4 :(得分:0)

使用TypeVisitor, 使用此方法接受数组类型:

 /**
 * Visits an array type.
 * @param t the type to visit
 * @param p a visitor-specified parameter
 * @return  a visitor-specified result
 */
R visitArray(ArrayType t, P p);