如何使用Java泛型方法? 我正在从C++到java。现在我正在尝试一种泛型方法。但是编译器总是抱怨下面的错误

如何使用Java泛型方法? 我正在从C++到java。现在我正在尝试一种泛型方法。但是编译器总是抱怨下面的错误,java,generics,Java,Generics,对于类型T HelloTemplate.java/HelloTemplate/src/HelloTemplate,未定义getValue()方法 错误指向t.getValue()行 据我所知,T是MyValue类,它具有getValue方法 怎么了?我怎样才能解决这个问题。我正在使用Java1.8 public class MyValue { public int getValue() { return 0; } } public class HelloTemp

对于类型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));
   }

}
公共类MyValue{
public int getValue(){
返回0;
}
}
公共类HelloTemplate{
静态int getValue(T){
返回t.getValue();
}
公共静态void main(字符串[]args){
MyValue mv=新的MyValue();
系统输出打印LN(getValue(mv));
}
}

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

只有当您添加绑定到泛型类型参数
T
的类型时,它才会知道:

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

只是在调用方法之前需要强制转换<代码>返回((MyValue)t).getValue() ,以便编译器可以知道它正在调用MyValue的方法

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

C++模板与java泛型的区别:
   static <T> int getValue(T t) {
        return ((MyValue) t).getValue();
    }
  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.