Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList of classes : ArrayList<Class> but how to force those classes to extend some super class?

Tags:

java

I want to manage an ArrayList of classes.

For instance, I have 3 types of filters : TextFilter, DurationFilter and TimeFilter which extend Filter.

That seems to be correct :

List<Class> filters = new ArrayList<Class>();

filters.add(TextFilter.class);
filters.add(DurationFilter.class);
filters.add(TimeFilter.class);

But now I want to restrain the ArrayList type with

List<Filter.class> filters = new ArrayList<Filter.class>();

filters.add(TextFilter.class);
filters.add(DurationFilter.class);
filters.add(TimeFilter.class);

But it seems that it is not correct. Can you explain why? Do you have a solution to only accept Filter child classes to be adde in my ArrayList? Thanks.

like image 501
Julien Avatar asked May 07 '13 13:05

Julien


2 Answers

Use a ? in generics.

List<Class<? extends Filter>> filters = new ArrayList<Class<? extends Filter>>();

Since you want class objects and not the instances.

like image 86
Sri Harsha Chilakapati Avatar answered Oct 11 '22 14:10

Sri Harsha Chilakapati


You should be able to say List<Class<? extends Filter>>

See Upper Bounded Wildcards

like image 44
Julien Langlois Avatar answered Oct 11 '22 14:10

Julien Langlois