Lukasz Kujawa
Lukasz Kujawa

Reputation: 3096

Collection of Class and inheritence

I would like to have a collection of Class'es of a specific subtype to achieve something like this:

public class Test {
    private class Parent {}
    private class Child1 extends Parent{}
    private class Child2 extends Parent{}

    List<Class<Parent>> classes = new ArrayList();

    public Test() {
        classes.add(Child1.class); 
    }

    public static void main(String[] args) {
        new Test();

    }
}

How to achieve the above without upsetting the compiler?

Upvotes: 1

Views: 61

Answers (2)

fabian
fabian

Reputation: 82461

Use

List<Class<? extends Parent>> classes = new ArrayList<>();

This

List<Class<Parent>> classes = new ArrayList();

"upsets" the compiler, since it requires the elements of the list to be of type Class<Parent>. However Child1.class is of type Class<Child1>. Note that Class<Child1> does not extend Class<Parent>.

Upvotes: 10

Thomas
Thomas

Reputation: 88727

Change your list definition to List<Class<? extends Parent>> and the compiler should be happy. This would define the list to contain any class that extends Parent, i.e. Parent and subclasses.

Note that List<? extends Class<Parent>> would not work since you can't extend Class and even if you could the list might then actually be an ArrayList<Class<Child1>> and thus the compiler wouldn't let you add elements to the list.

Upvotes: 4

Related Questions