java - Passing a class type to a method, then casting to that type? -


i'm still pretty new java, might missing obvious here.

i have following code use pick class types list of entities:

public array<?> pickentities(class<?> cls) {     array<? super spriteentity> allentities = new array<object>();     (spriteentity entity : mygame.allentities) {         if (entity.getclass() == cls) {                 allentities.add(entity);         }     }     return allentities; } 

that works fine, means when calling method still need cast class on other side. example:

asteroid = (asteroid)pickentities(asteroid.class); 

what use class passing pickentities class (the cls parameter) , cast returning array (allentities) that type.

is there way this? whenever try tells me 'cls' not type , can't used cast.

your method should generic:

public <t extends spriteentity> list<t> pickentities(class<t> clazz) {     list<t> result = new arraylist<t>();     (spriteentity entity : mygame.allentities) {         if (entity.getclass() == clazz) {             result.add((t) entity);         }     }     return result; } 

note used standard collection classes, , standard java naming conventions.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -