Pergunta

Possible Duplicate:
Class.getArrayType in Java?

I need to get the class for a type that is represented by a string. I am trying to invoke getMethod and I only have a list of strings for the types it requires.

Class.forName(str) works when str is a simple class, but not, for example, with an array like so:

Class<?>[] typeClasses = new Class<?>[]{Class.forName("my.type.class[]")};
Method method = someClass.getMethod(methodString, typeClasses);
Foi útil?

Solução

One way to get hold of the Class object for an array type is to call getClass() on an array instance that you created reflectively; e.g.

Class someClass = Some.class;
Class someArrayClass = java.reflect.Array.newInstance(someClass, 0).getClass();

You can also use Class.forName() but you need to specify the class name in internal form; e.g. the class name for an Object[] is "[Ljava.lang.Object;". See Class.getName() for details of the class name format.

Outras dicas

The problem is the string you're passing in the example is not the correct string representation of that class. This example code runs fine and prints true:

String[] array = new String[] { "hello" };
Class<?> arrayClass = array.getClass();
String stringClass = arrayClass.getName();
Class<?> parsedClass;
try {
    parsedClass = Class.forName(stringClass);
} catch (ClassNotFoundException e) {
    throw new RuntimeException(e);
}
System.out.println(arrayClass.equals(parsedClass));

See the Javadoc for Class#getName() for examples on how to represent array types as strings. If these strings are coming from somewhere else and you know what format to expect you could write a method to convert the strings into the format expected by the classloader.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top