Usul
Usul

Reputation: 287

Get type of class for array from TypeMirror

I am doing Java APT and want to parse a method (an ExecutableElement). Now I need the return type of the method. I do not know how to get the type, if it is an array.

Example: String[] foobar()

I want to get the type String.

From the ExecutableElement instance, I can get the return-type as an instance of TypeMirror (using getReturnType()). But if it is an array, I can not get the "real type" (in my example: String).

I tried:

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());

Which gives me:

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

I would like an instance of java.lang.Class, representing java.lang.String (in my example).

Upvotes: 5

Views: 4201

Answers (5)

kehw_zwei
kehw_zwei

Reputation: 13

use TypeVisitor, use this method to accept array type:

 /**
 * 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);

Upvotes: 0

user6881430
user6881430

Reputation: 21

I solved the problem like this:

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

tm.toString() has e.g. value: "java.lang.String"

Upvotes: 2

bennyl
bennyl

Reputation: 2946

I know this is an old question but all the answers here are considering reflection and not TypeMirror which is part of the annotation processing api and not reflection.

To get the component type from a typeMirror you must cast it into ArrayType and call the method ArrayType::getComponentType() i.e.,

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

Upvotes: 7

pasha701
pasha701

Reputation: 7207

Method "getComponentType" is worked fine:

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());
    }
}

Output is: class java.lang.String

Upvotes: 1

subash
subash

Reputation: 3140

this is you want

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

its print String[]

but you want String you must give the index.

for example System.out.println(pReturnType[i].getClass().getSimpleName());

Upvotes: 0

Related Questions