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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With