Get the return Type for inherited generic method

耗尽温柔 提交于 2019-12-24 17:06:10

问题


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();

回答1:


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();



回答2:


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.



来源:https://stackoverflow.com/questions/58482157/get-the-return-type-for-inherited-generic-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!