简体   繁体   中英

Casting Generic

Is it possible to cast a generic object to something like a string?

I thought casting generics would be similar to normal object casting like:

public String tempString;
public E genericObject;

tempString = ((String) genericObject);

however, when compiling I still get a incompatible type error.

required: String 
found:    E

You can do what you want, but you need to go via another cast first:

public String tempString;
public E genericObject;

tempString = (String) ((Object) genericObject);

The issue is that you can't cast "sideways" in a hierarchy, you can only cast down. That is, you can cast from Object to String , but not from Number to String .

Note, that if E really isn't a string, you will get a ClassCastException , however if you are only doing this in circumstances that you know that E is really a string, then you will be fine.

You can. However only if E and String are compatible.

During runtime the JIT "replaces" the type E with the actual type you have chosen during class creation. If you for example created the generic class with Integer as E, your code becomes:

public String tempString;
public Integer genericObject;

tempString = ((String) genericObject);

That is why it won't work.

If you want to make sure the generic is castable to a specific class, you can limit the possible generic types in the form generic<E extends String> (there is however no class in Java that extends String).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM