Reputation: 348
For my project, I have a HashMap with Class<?>
as key and MyClass
as value.
Map<Class<?>, MyClass> map = new HashMap<Class<?>, MyClass>();
As an example, I put in some values:
map.put(EntityDamageEvent.getClass(), new MyClass());
This is the inheritance tree for this key:
class EntityDamageByEntityEvent extends EntityDamageEvent
class EntityDamageEvent extends EntityEvent
class EntityEvent extends Event
The problem arises when I try to get a value from the map, but the key happens to be a subclass of the key I'm actually trying to use:
void doSomething() {
EntityDamageByEntityEvent event = new EntityDamageByEntityEvent();
post(event); //This returns null
}
MyClass post(Event event) {
return map.get(event.getClass());
}
Object.getclass()
gives me the subclass, and not the class that I want.
How should I tackle this problem? Thanks
Upvotes: 2
Views: 138
Reputation: 348
Thanks for the help guys, I have done this:
public void post(Event event, Class<?> type) {}
this.post(new EntityDamageByEntityEvent(), EntityDamage.class);
Upvotes: 0
Reputation: 15418
A different idea:
Use the HashMap<String, MyClass>
where the key is to be inserted with the Class's fully qualified name: SubClass.class.getName()
. While retrieving, you can use Class.forName(key)
to find the correct class.
Upvotes: 0
Reputation: 12398
Iterate over the subclass ancestors, until you find someone that is in the map.
for (Class<T> klass = event.getClass(); klass!=null; klass=klass.getSuperclass()) {
MyClass c = map.get(klass);
if (c!=null) return c;
}
return null;
Upvotes: 2
Reputation: 7559
Replace
EntityDamageByEntityEvent event = new EntityDamageByEntityEvent();
with
Event event = new Event();
Upvotes: 0