<分区>
我想找到一个 hack 来在运行时推断另一个实例的 var 的实际通用实例,没有:
- 更改我需要的方法签名(添加辅助参数
Class<T>
,最明显的方法) 不得不
instanceof
以硬编码方式显示所有可能的子类型MyInterface<? extends Number> myInterface = whateverReturnsWildcardDoubleInterface(); Class<?> type = inferInstanceType(myInterface); assert type == Double.class; /** This is the method that represents the code I am looking for with the conrete signature**/ public <T extends Number> Class<T> inferInstanceType(MyInterface<T> myInterface){ return T.class; //Concrete T (can or cannot be the very Number) }
理想情况下,当 T 是特定子类型 Integer,Double.. 时它应该返回 Double,当 T 是 Number 时它应该返回 Number
我检查了反射,几个“TypeResolver”/“GenericResolver”库(如 Spring 中的库或 Github 中的其他库),但我找不到破解它的方法。
编辑:我得出的结论是,他唯一可行的方法是通过堆栈跟踪进行某种非常复杂的反射,直到在实例化中传递类型的实际行
EDIT2:我知道这很愚蠢...但我通过简单地添加 T getT()
解决了它方法到我的界面,所以我可以 return myInterface.getT().getClass()