Reputation: 2472
Is it possible to create a collection of different class types, so that an object can be later checked to see if it is an object of any of these classes in the collection? something like:
for(Class c: collectionOfClasses){
if(o.getClass() == c){
//do something
}
}
Here, o is some object. I tried it out by using:
private LinkedList<Class> collectionOfClasses...
Eclipse gives a warning "Class is a raw type.References to generic type Class should be parameterized." Any safe way of doing what I want to do?
EDIT #1
Actually I have objects of different classes (which do not form a hierarchy), moving about. They all have a certain radius. A particular object can connect with other objects in its radius only if the other object falls into one of its known classes.could i make myself clear?
EDIT #2
A good example of what I want to do: Let's say I speak English and French. But I can identify different humans around me. Let's say I see 10 people near me. Then I will try to test if p1.getClass() is either English or French, p2.getClass() is either English or French. After all the humans around me are examined, I will talk to those who understand either English or French.
Upvotes: 5
Views: 9888
Reputation: 13924
The for loop is not necessary. It's shorter just to write
if(collectionOfClasses.contains(o.getClass())) {
//do something
}
Upvotes: 0
Reputation: 2785
Class is a generic type; to say you want 'any' kind of class, you would use the wildcard "?":
List<Class<?>> theList = ...
Upvotes: 1
Reputation: 9652
You can use:
private LinkedList<Class <?>> collectionOfClasses...
And if you have anything more specific, you can try:
private LinkedList<Class <? extends MyInterface>> collectionOfClasses...
Upvotes: 10
Reputation: 11308
You can use ArrayList<Class<?>>
.
For example:
List<Class<?>> list = new ArrayList<Class<?>>();
list.add(String.class);
list.add(x.getClass());
Upvotes: 3