1

Is it at all possible to cast a generic class's type to a given Class object in java? Something like this:

public ModelBin<?> getModelBin(Class type) {
    return (ModelBin<type>) entities.get(type);
}

The compiler tells me that it can't resolve type to a type. I know I could just do this,

public ModelBin<?> getModelBin(Class type) {
    return entities.get(type);
}

and it would work but then I would have to cast each model out of the model bin later on in the program - which is more work.


I did some more reading and ended up with this:

public <T> ModelBin<T> getModelBin(Class<T> type) {
    return (ModelBin<T>) entities.get(type);
}

Would this have the funciton return a ModelBin<type> object?

4
  • entities is a HashMap<Class, ModelBin<?>> Commented Aug 28, 2017 at 22:00
  • 1
    There isn't any type-safe solution. You'll have to ensure the map can only contain valid mappings. Also, use Class<?> instead of the raw Class. Commented Aug 28, 2017 at 22:01
  • With type erasure this is a lot more difficult, as at runtime you may not be able to be sure that the type is an instance of ModelBin<T> | docs.oracle.com/javase/tutorial/java/generics/erasure.html Commented Aug 28, 2017 at 22:07
  • The purpose of this structure is to sort various entities to be rendered on screen via various shader - depending on Class<T> type - so I "know" what will be stored in the Map Commented Aug 28, 2017 at 22:09

2 Answers 2

1
public <T> ModelBin<T> getModelBin(Class<T> type) {
    return (ModelBin<T>) entities.get(type);
}

This is the generally-accepted way to do this in a type-safe manner.

final ModelBin<String> myStrBin = getModelBin(String.class); 

will compile correctly.

Would this have the function return a ModelBin object?

This will look correct to the compiler, yes. At runtime, the returned ModelBin won't have a type (due to erasure), but that's just the way that Java is designed.

Sign up to request clarification or add additional context in comments.

Comments

0

No, it is not possible and the reason is Type Erasure. In your code it decides using runtime values what class to cast to, an due to Type Erasure type parameters are not available at that time (only compilation).

Another example of Type Erasure

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.