简体   繁体   中英

Generic method in Java, determine type

I would like to be able to detirmine the return type of my method call at runtime, but I can not seem to be able to get the Type of T.

    public <T> T getT()
    {
        Object t = null;
        Class<?> c = t.getClass();
        System.out.println(c.getName());
        return (T) t;
    }

Is there any way to determine the Type of T at runtime in Java?

Your function will throw a NullPointerException, because you call "getClass" on a null pointer (since t is initialized with null). Additionally, generics are used for giving added compile-time type-checking. They do not give you anything special at runtime; generics simply use type Object, but cause the code which uses the generic object to perform implicit casts and also causes the compiler to be aware of how you will use it.

Java generics are a static type checking feature. Attempting to retrieve reflection artifacts from generic parameters is typical of poorly thought out design.

In the question example, there is no guarantee that T is a class or even interface. For example

List<? extends Frogs> list = thing.getT();

If you really want to go down this path (and I strongly suggest you don't, not that I expect you to take any notice), then you can supply a reflection object that is statically related to the generic parameter as an argument:

 public <T> T getT(Class<T> clazz) {
     Object value = map.get(clazz);
     return clazz.cast(value);
 }

If you have a generic Class you can write a constructor that takes the type and saves it into a member of your class. This way you can check the Type during runtime. All information that are only in the generics are gone after compiling.

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