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
object?

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.
        bar.add(cls.cast(givenObject));
        Integer y = 6;
        bar.add(y);
    }
}

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)) {
        list.add(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

BAT均已开始布局区块链,探寻区块链生态和医疗区块链的盈利前景

上一篇

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

下一篇

你也可能喜欢

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

长按储存图像,分享给朋友