简体   繁体   English

如何从 Java 中的泛型类型中获取方法?

[英]How to get method from generic Type in Java?

I have a problem like below:我有如下问题:

List<T> someList;

for(T element : someList){
    System.out.println(element.getName()); //cannot resolve method 'getName'
}

how to get method from generic type?如何从泛型类型中获取方法?

my T is a class where I have many parameters with setters and getters,我的T是 class ,其中我有许多带有 setter 和 getter 的参数,

can someone tell me how to get some params from T class?有人可以告诉我如何从T class get一些参数吗?

thanks for any help谢谢你的帮助

T needs to be upper-bounded to a type which has the getName() method. T需要是具有getName()方法的类型的上限。

For example:例如:

interface HasGetName {
  String getName();
}

Then add your upper-bound using T extends HasGetName :然后使用T extends HasGetName添加您的上限:

// If T is a class-level type variable:
class YourClass<T extends HasGetName> {
  List<T> someList;

  void print() {
    for(T element : someList){
      System.out.println(element.getName());
    }
  }
}

// If T is a method-class-level type variable:
class YourClass {
  <T extends HasGetName> void print(List<T> someList) {
    for(T element : someList){
      System.out.println(element.getName());
    }
  }
}

The safest way would be something like:最安全的方法是:

List<T> someList;

for(T element : someList){
    if (element instanceof SpecializedElement)
        System.out.println(((SpecializedElement)element).getName());
}

Java 15 introduces something cool List someList; Java 15 介绍了一些很酷的东西 List someList;

for(T element : someList){
    if (element instanceof SpecializedElement s)
        System.out.println(s.getName());
}

You don't need to do any casting with instanceof + class + any var name您不需要使用 instanceof + class + 任何 var name 进行任何转换

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

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