简体   繁体   中英

How to use Java generics method?

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

}

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

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 instanceof operator, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM