2

I am moving from C++ to Java. Now I am trying a generics method. But the compiler always complains below error

The method getValue() is undefined for the type T HelloTemplate.java /helloTemplate/src/helloTemplate

The error was pointing to t.getValue() line As I understand, T is class MyValue, which has the method getValue

What is wrong? How Can I fixed this. I am using 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));
   }

}
bzhu
  • 908
  • 2
  • 9
  • 16
  • For the diffrence between C++ template and Java generics: https://stackoverflow.com/questions/36347/what-are-the-differences-between-generic-types-in-c-and-java – bzhu Mar 28 '19 at 01:43

2 Answers2

6

The compiler doesn't know that you are going to pass to getValue() an instance of a class that has a getValue() method, which is why t.getValue() doesn't pass compilation.

It will only know about it if you add a type bound to the generic type parameter T:

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

Of course, in such a simple example you can simply remove the generic type parameter and write:

static int getValue(MyValue t) {
    return t.getValue();
}
Eran
  • 387,369
  • 54
  • 702
  • 768
3

Just you need casting before calling the method. return ((MyValue) t).getValue(); , so that compiler can know that it's calling the MyValue's method.

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

in case of multiple classes, you can check for instances using instanceofoperator, and the call the method.. like below

  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.
Jabongg
  • 2,099
  • 2
  • 15
  • 32