我正在做 Java APT 并想解析一个方法 (an ExecutableElement)。现在我需要该方法的返回类型。我不知道如何获取类型,如果它是一个数组。
例子: String[] foobar()
我想得到类型String。
从 ExecutableElement 实例中,我可以获得作为 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());
Run Code Online (Sandbox Code Playgroud)
这给了我:
TEST: java.lang.String[]
TEST2: com.sun.tools.javac.code.Type$ArrayType
TEST3: class com.sun.tools.javac.code.Type
TEST4: null
TEST5: ARRAY
Run Code Online (Sandbox Code Playgroud)
我想要一个java.lang.Class, 代表java.lang.String(在我的例子中)的实例。
我知道这是一个老问题,但这里的所有答案都在考虑反射,而不是 TypeMirror,后者是注释处理 api 的一部分,而不是反射。
要从 typeMirror 获取组件类型,您必须将其强制转换ArrayType并调用该方法,ArrayType::getComponentType()即,
TypeMirror pReturnType = ...
if (pReturnType.getKind() == TypeKind.ARRAY) {
return ((ArrayType)pReturnType).getComponentType();
} else {
//this is not an array type..
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2929 次 |
| 最近记录: |