mercredi 26 juillet 2017

Instantiate a Java type parameter/ generic using a Class object

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<Integer> foo = new ArrayList<Integer>();

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<Integer.class> foo = new ArrayList<Integer.class>();

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<cls> bar = new ArrayList<cls>();

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

        // 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);
    }
}





Aucun commentaire:

Enregistrer un commentaire