我正在从 C++ 转向 Java。现在我正在尝试泛型方法。但编译器总是报以下错误
The method getValue() is undefined for the type T HelloTemplate.java /helloTemplate/src/helloTemplate
错误指向 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));
}
}
最佳答案
编译器不知道您要向 getValue()
传递一个具有 getValue()
方法的类的实例,这就是为什么 t.getValue()
未通过编译。
只有当您添加绑定(bind)到泛型类型参数的类型时,它才会知道它T
:
static <T extends MyValue> int getValue(T t) {
return t.getValue();
}
当然,在这样一个简单的示例中,您可以简单地删除泛型类型参数并编写:
static int getValue(MyValue t) {
return t.getValue();
}
关于java - 如何使用Java泛型方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55374579/