简体   繁体   中英

Determine the type of a generic class at Runtime

I am aware of the fact that the site is fraught with similar questions and that by a quick reading of the given question the first answer coming to mind is "No, you can 't", but I still have the impression that what I am asking is not impossible by any means.

I have created a generic method in a class and I want to get check the type of the Object passed to the method. I know that it cannot be done directly, hence I pass an object Class<T> obj to the method. However I cannot find the way to perform properly the type-checking in the method body.

public <T> void readData(T obj1, Class<T> obj2){
}   

Assuming that T is always of one of three types: ClassA , ClassB or ClassC . How should the if-else-if block look like?

Use obj2.cast(obj1) , which casts obj1 to the class or interface represented by obj2 , returns obj1 if obj1 is assignable to the type T (note that null is assignable to any type), and throws ClassCastException otherwise.

We are not interested in the result of the cast, because the statically known type of obj1 is already T and obj2.cast(obj1)==obj1 (if the cast succeeds). However, if the cast fails, an early exception will be thrown.

Example:

public <T> void readData(T obj1, Class<T> obj2){
 obj2.cast(obj1); 
 //... 
}   

The following invocation (where there is an unchecked cast from Class<?> to Class<String> ) will fail:

readData("Hello",(Class<String>)(Class<?>)Integer.class);

The method cast is also useful for replacing unchecked casts, for instance:

public <T> void readData(Object obj1, Class<T> obj2){
 T t = (T)obj1;//BAD: unchecked cast
 //...
}


public <T> void readData(Object obj1, Class<T> obj2){
 T t = obj2.cast(obj1());//GOOD: ClassCastException if the cast fails
 //...
}

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