Creating ArrayList of a Class defined in a variable

Suppose I have something like this

Class klazz = Integer.class;

And I'm interested in doing something like this

List<(klazz Class)> something = new ArrayList<>();

something.add(new Integer(..))
something.add(new Integer(..))
.. etc

I probably need to use reflection, yet however, I'm unsure about how to apply it.

Is it possible to do without reflection? If it's not, how would you find it suitable to implement?

Thanks in advance

Upvotes: 1

Views: 73

Answers (1)

J-Alex
J-Alex

Reputation: 7107

I cannot completely undertand the requirement, but this may help:

public class Main {
    public static void main(String[] args) {
        ContainerWrapper<Integer> containerWrapper = new ContainerWrapper<>(Integer.class);
        containerWrapper.add(1);
        System.out.println(containerWrapper.containerType());
        System.out.println(containerWrapper.isInteger());
    }
}

class ContainerWrapper<T> {
    // Store type information here
    private Class<T> clazz;
    private List<T> list = new ArrayList<>();

    public ContainerWrapper(Class<T> clazz) {
        this.clazz = clazz;
    }

    public void add(T element) {
        list.add(element);
    }

    public Class<T> containerType() {
        return clazz;
    }

    public boolean isInteger() {
        return clazz.isAssignableFrom(Integer.class);
    }
}

You can check T type using clazz.isAssignableFrom(*.class)

Output:

class java.lang.Integer
true

Upvotes: 2

Related Questions