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));
   }

}
1

2 Answers 2

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();
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.