Instantiate a Java-based parameter / generic using a Class object


Instantiate a Java-based parameter / generic using a Class object

This question already has an answer here:

  • How to set the generic type of an ArrayList at runtime in java? 4 answers

How do you instantiate a Java generics Object that takes type parameters given only a Class
or Class

For example: Normally one can instantiate an ArrayList
of Integer
objects using the following syntax:

ArrayList foo = new ArrayList();

However, given a Class
object such as Integer.class
, how could one create a similar ArrayList
? For example, how would I do something like this (incorrect syntax):

ArrayList foo = new ArrayList();

I need this for something very unusual I am doing with Java (Creating an open-source tool for visualizing user-supplied instances of data structure/ generic classes they write). Here is an example of how I would be using this code which illustrates the information I would be given:

import java.util.ArrayList;
import java.util.List;

public class ArrayListFromClass {
    // obviously this code does not work
    public static void main(String[] args) {
        Object givenObject = new Integer(4);
        // I would not know it is Integer.class, a Class object would be supplied by the user/ as a generic
        Class cls = givenObject.getClass();
        List bar = new ArrayList();

        // Where args[0] is "Integer.class"
        List foo = new ArrayList();

        // then I would be able to add to foo or bar with one or both of these techniques:
        // printing givenObject.getClass() gives you java.lang.Integer, don't worry about the casting not working.
        Integer y = 6;

Java is statically typed. The reason you would want to instantiate an ArrayList like so:

ArrayList foo = new ArrayList();

is to let your IDE/compiler know that whenever something other than Integer
is put into the list, show an error. Other than that the internals will ignore this initialization, in fact even erase the type

So when you get your Class
object at runtime, you only know the type of the class when your code actually runs. So the IDE/Compiler wouldn’t be able to warn you before runtime whether there is something wrong in your code.

So a List
will do just fine in your case. If you want type safety you will have to check on your own like so:

String sampleString = "String";
    Class clazz = sampleString.getClass();
    if (clazz.isInstance(sampleString)) {

.isInstance(Object obj)
is the equivalent of instanceof
when you actually have a Class
at hand.


Instantiate a Java-based parameter / generic using a Class object



滴滴回应小股东被自家平台司机殴打 4000亿独角兽之殇



Instantiate a Java-based parameter / generic using a Class object