简体   繁体   English

使用反射在方法中查找通用参数的类型

[英]Find type of generic parameter in method using reflection

How Can i Find Foo and generic class for read method using reflection? 如何使用反射找到Foo和泛型类以进行读取方法?

 public void contactUsAvail(List<Foo> list) {
       // method block
    }

You can't, as the parameter type Foo is erased at compile time. 您不能这样做,因为参数类型Foo在编译时会被擦除。 Type parameters are compiler hints only in Java and are not retained for execution. 类型参数仅是Java中的编译器提示,不会保留执行。

But you could give your method a hint by passing in Foo as a method parameter: 但是您可以通过将Foo作为方法参数传递给方法一个提示:

public void <F extends Foo>contactUsAvail(Class<F> type, List<F> list) {
    if(SubclassOfFoo.class.isAssignableFrom(type)) {
        //all elements in 'list' inherit from 'SubclassOfFoo'
    }
}

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

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