1

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

11
  • 7
    Type parameters help you at compile time only. At run time, they disappear. So setting the type parameter at run time, based on different values of klazz doesn't really fit how generics work. I'd suggest just using a List<Object> and having some logic to ensure that only objects of type klazz go into it. Commented May 23, 2018 at 0:11
  • please, if possible add it as a response. I'll check it out later and assign at as response if there's nothing useful yet Commented May 23, 2018 at 0:14
  • What do you expect to happen if klazz is String.class? Commented May 23, 2018 at 0:22
  • I expect something to be List<String> Commented May 23, 2018 at 0:23
  • List<Class> supposed to add only Class elements, new Integer(..) will not fit into this. Commented May 23, 2018 at 0:28

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

3 Comments

You have Integer hardcoded here: ContainerWrapper<Integer>, is there any way this could be dynamically set by a Class variable? If not then I'd have to stick to use no generics at all, but it's not considered good practice.
Only like ContainerWrapper<Object>, as was proposed in the first comment.
It's nothing different than List<T>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.