【问题标题】:How to use Java generics method?如何使用 Java 泛型方法?
【发布时间】:2019-08-17 20:46:01
【问题描述】:

我正在从 C++ 迁移到 Java。现在我正在尝试一种泛型方法。但是编译器总是报以下错误

类型 T HelloTemplate.java /helloTemplate/src/helloTemplate 的方法 getValue() 未定义

错误指向t.getValue() 行 据我了解,T 是 MyValue 类,具有 getValue 方法

怎么了?我该如何解决这个问题。我正在使用Java1.8

public class MyValue {

    public int getValue() {
       return 0;
    }
}

public class HelloTemplate {

    static <T> int getValue(T t) {
        return t.getValue();
    }
    public static void main(String[] args) {
       MyValue mv = new MyValue();
       System.out.println(getValue(mv));
   }

}

【问题讨论】:

标签: java generics


【解决方案1】:

编译器不知道您将向getValue() 传递一个具有getValue() 方法的类的实例,这就是t.getValue() 没有通过编译的原因。

只有添加绑定到泛型类型参数T的类型才会知道:

static <T extends MyValue> int getValue(T t) {
    return t.getValue();
}

当然,在这样一个简单的示例中,您可以简单地删除泛型类型参数并编写:

static int getValue(MyValue t) {
    return t.getValue();
}

【讨论】:

    【解决方案2】:

    只是你需要在调用方法之前进行强制转换。 return ((MyValue) t).getValue(); ,以便编译器知道它正在调用 MyValue 的方法。

       static <T> int getValue(T t) {
            return ((MyValue) t).getValue();
        }
    

    在多个类的情况下,您可以使用instanceofoperator 来检查实例,并调用方法.. 如下所示

      static <T> int getValue(T t) {
            //check for instances
            if (t instanceof MyValue) {
                return ((MyValue) t).getValue();
            }
            //check for your other instance
      return 0; // whatever for your else case.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-01
      • 2013-04-17
      • 2016-03-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多