Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm still pretty new to Java, so I might be missing something obvious here.

I have the following code that I use to pick class types from a list of all my entities:

public Array<?> PickEntities(Class<?> cls) {
    Array<? super SpriteEntity> allEntities = new Array<Object>();
    for (SpriteEntity entity : MyGame.AllEntities) {
        if (entity.getClass() == cls) {
                allEntities.add(entity);
        }
    }
    return allEntities;
}

That works fine, but it means that when calling this method I still need to cast it to the class on the other side. For example:

asteroid = (Asteroid)PickEntities(Asteroid.class);

What I would like to do is use the class I am passing to my PickEntities class (the cls parameter) and then cast the returning array (allEntities) to that type.

Is there a way to do this? Whenever I try it just tells me that 'cls' is not a type and can't be used to cast.

like image 944
boolean Avatar asked May 18 '13 14:05

boolean


People also ask

Which is used for casting of object to a type or a class?

Type Casting is a feature in Java using which the form or type of a variable or object is cast into some other kind of Object, and the process of conversion from one type to another is called Type Casting.

Can a class be casted to an interface?

Yes, you can. If you implement an interface and provide body to its methods from a class. You can hold object of the that class using the reference variable of the interface i.e. cast an object reference to an interface reference.

How can we convert one class object to another class in Java?

gson. Gson for converting one class object to another. First convert class A's object to json String and then convert Json string to class B's object. Save this answer.

Why we go for type casting in Java?

Understanding Type Casting in JavaProgrammers need to check the compatibility of the data type they are assigning to another data type, in advance. Typecasting is automatically performed if compatibility between the two data types exists. This type of conversion is called automatic type conversion.


1 Answers

Your method should be generic:

public <T extends SpriteEntity> List<T> pickEntities(Class<T> clazz) {
    List<T> result = new ArrayList<T>();
    for (SpriteEntity entity : MyGame.allEntities) {
        if (entity.getClass() == clazz) {
            result.add((T) entity);
        }
    }
    return result;
}

Note that I used standard collection classes, and standard Java naming conventions.

like image 174
JB Nizet Avatar answered Oct 19 '22 19:10

JB Nizet