How to return an instance of Class for an array of a given Class subtype?

Marco Altieri :
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.Date;

public class Test {
    public static void main(String[] args) {
        System.out.println(new Test().getClassOfArrayOfSerializable(String.class));
        System.out.println(new Test().getClassOfArrayOfSerializable(Date.class));
    }

    @SuppressWarnings("unchecked")
    private Class<? extends Serializable> getClassOfArrayOfSerializable(final Class<? extends Serializable> subtypeClass) {
        return (Class<Serializable>) Array.newInstance(subtypeClass, 0).getClass();
    }
}

The method getClassOfArrayOfSerializable() above, returns the class for an array of an object of the type passed as the argument.

As you can see, I had to create an instance of the array even though I actually need only its Class.

Is there a way to avoid the instantiation of the array?

Rann Lifshitz :

Turns out that the following works quite well (tested and verified using an online compiler):

System.out.println(String[].class);
System.out.println(Date[].class);

Results in the desired output:

class [Ljava.lang.String;
class [Ljava.util.Date;

No need for the instantiation of the array - assuming you know in advance what class you will require, you can simply request the class type of its encapsulating array.

However, if you must find the array class type during runtime on a given class type, I believe your only option would be to use basin's suggestion of (also verified as a working solution via an online compiler):

Class.forName("[L" + className + ";");

And as a method:

 @SuppressWarnings("unchecked")
    private Class<? extends Serializable> getClassOfArrayOfSerializableNoArrayInitialization
        (final Class<? extends Serializable> subtypeClass) throws ClassNotFoundException
    {
        return (Class<Serializable>) Class.forName("[L" + subtypeClass.getName() + ";");
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=157671&siteId=1