简体   繁体   中英

Get the return Type for inherited generic method

I have these 3 classes

public class Box<O> {

    public O getItem() {...}

}
public class CoolBox extends Box<Integer> { ... }
public class AmazingBox extends CoolBox { ... }

At one point in my code, I need to get the return Type of the method getItem() for the AmazingBox class, but when accessing its methods via reflection, I get Object as the return Type instead of Integer .

Is there any way, (plain java or extra libraries) to get Integer as the return Type?

This is the code I used to get the return type:

Class<?> c = AmazingBox.class;  // This is not how i get the class but its for demonstration purposes

Method m = c.getMethod("getItem");

Type t = m.getReturnType();

I just discovered that there is a library called GenericsResolver that does exactly what I want.

Using this piece of code it returns the correct type

Class<?> clazz = AmazingBox.class;
GenericsContext genericsContext = GenericsResolver.resolve(clazz);
Method method = clazz.getMethod("getItem");
Type methodReturnType = genericsContext.method(method).resolveReturnType();

While inheriting you can use generics for inheriting classes and create lower or upper bounds accordingly. If you don't do that assume you are working without using generics and won't get type safety on inheriting non-generic classes.

In short, if you go hybrid, type erasures will become effective with following rules (ref- oracle documentation)

Type Erasure

Generics were introduced to the Java language to provide tighter type checks at compile time and to support generic programming. To implement generics, the Java compiler applies type erasure to:

  • Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods.
  • Insert type casts if necessary to preserve type safety.
  • Generate bridge methods to preserve polymorphism in extended generic types.

Type erasure ensures that no new classes are created for parameterized types; consequently, generics incur no runtime overhead.

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