I'm trying to iteate over a map and cast objects, then somehow reference them as already casted.
Assume Test1
and Test2
are totally different classes, but both have a method named equally get_class_specific_field()
HashMap<Class,Object> objects = new HashMap<>();
then inside Test1
and Test2
classes I do respectively:
objects.put(Test1.class,this);
objects.put(Test2.class,this);
This is a normal way of iterating:
for( Map.Entry<Class, Object> entry : objects.entrySet()){
if(Object instanceof Test1){
Test1 castedObj = (Test1)entry.getValue();
castedObj.get_class_specific_field();
}
if(Object instanceof Test2){
Test2 castedObj = (Test2)entry.getValue();
castedObj.get_class_specific_field();
}
}
Is it possible to somehow avoid if blocks, e.g.
for( Map.Entry<Class, Object> entry : objects.entrySet()){
???? castedObj = entry.getValue()).cast(entry.getKey());
castedObj.get_class_specific_field();
}
Is there any other way of doing this?
Aucun commentaire:
Enregistrer un commentaire