简体   繁体   English

从getDeclaredMethods查找具有实际类型的通用方法

[英]Find generic method with actual types from getDeclaredMethods

I have generic classes that look like: 我有类似的通用类:

interface X<Input, Output>
{
  Output process(Input input);
}

class Y implements X<Integer, Float> 
{   
  Float process(Integer input); 
}

I use getDeclaredMethods to find process on Y just with its name (not the arguments, on purpose). 我使用getDeclaredMethods来查找Y的过程,只是带有它的名称(不是故意的参数)。 When I look at the return Method[], process shows up twice, with Input=Object, Output=Object, and then with the actual instantiation types: Integer and Float. 当我查看return Method []时,该过程出现了两次,分别是Input = Object,Output = Object,然后是实际的实例化类型:Integer和Float。

Please note: I can see 1 function with Object,Object in the Method[] AND 1 function with the actual types I use to instantiate, like Integer,Float. 请注意:我可以在Method []中看到1个带有Object,Object的函数,还有1个带有我要实例化的实际类型的函数,例如Integer,Float。 So, the second function, which I'm interested in, is accessible from Method[]. 因此,我感兴趣的第二个函数可以从Method []访问。

What is the best way to get only the method with the actual types? 仅获取具有实际类型的方法的最佳方法是什么?

and then with the actual instantiation types. 然后使用实际的实例化类型。

That's not possible. 那不可能 You should see a single method whose parameter types are Object . 您应该看到一个参数类型为Object You can also look at the method's generic parameter and return types, and you will find that they are both type variables ( Input and Output are type variables). 您还可以查看该方法的通用参数和返回类型,您会发现它们都是类型变量( InputOutput都是类型变量)。

Subclasses of this class that inherit from it with specific type arguments for the type parameters, will have two methods: a method with the more specific parameter and return types, and a bridge method , with the original class's method's parameter and return types, in order to override it. 从该类继承并带有类型参数的特定类型参数的此类类将具有两种方法:具有更特定的参数和返回类型的方法 ,以及具有原始类的方法的参数和返回类型的bridge方法 (按顺序)覆盖它。 If you are asking how to ignore the bridge method, simply check if it's a bridge method ( .isBridge() ) 如果您询问如何忽略bridge方法,只需检查它是否为bridge方法( .isBridge()

Generic types are known only at compilation time. 泛型类型仅在编译时才知道。 Object is the actual type of generics at runtime, so you can't get them while running the program. Object是泛型在运行时的实际类型,因此在运行程序时无法获取它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM