4

I need to use reflection in my code, so my program doesn't break with every different version. I want to create a new instance of a class and the constructor that I want to use contains an array of a class. But that class also has to be found using reflection. This is an example of what I currently have.

Constructor<?> constructor = getClass("className").getConstructor(getClass("anotherClass"));

private Class<?> getClass(String name) {
    return Class.forName("my.package." + version + "." + name);
}

However the constructor doesn't use that class, but an array of that class, so how would I turn this class into an array type of it?

1 Answer 1

6

The Java Virtual Machine specification specifies the class names for array types. You could construct such a name and use Class#forName. However, the logic for the names differs between primitive types and reference types, so it might get annoying generating those String names.

Instead, you can construct an array of size 0 for the given type and use it to retrieve its type with getClass().

For example

Class<?> componentType = Class.forName("java.lang.String");
Class<?> arrayType = java.lang.reflect.Array.newInstance(componentType, 0).getClass();
System.out.println(arrayType);

will print

class [Ljava.lang.String;

arrayType will then hold the Class object for the given array type. You can use it to retrieve the constructor.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.