简体   繁体   中英

Java: different interfaces in generics

I have two classes (A and B) with identical methods (foo):

public class A {
 public String foo() {
  return "A said foo";
 }
}

public class B {
 public String foo() {
  return "B said foo";
 }
}

I want to make generic class which can call this method. But I have two ideas how to do this in runtime and haven't ideas about compile time:

  1. check for type and cast to A or B.

  2. Get method.

My example of generic which calls getMethod:

public class Template<T> {
 private T mT;

 public Template(T t) {
  mT = t;
 }

    public String bar() {
     String result = "no result";
  try {
      Method m = mT.getClass().getMethod("foo", null);
   result = (String)m.invoke(mT);
  } catch (Exception e) {
   result = e.toString();
   e.printStackTrace();
  }
  return result;
    }
}

Are there another way how to do it? I am looking for something like this:

public class Template<T extends A | B> {
...
}

Note, that I am not a creator of classes "A" and "B".

You'd have to make both classes implement a common interface declaring foo method. Java doesn't support so called "duck typing" which would be helpful here.

You will have to create an interface and let your Template accept any class which implements the interface.

interface Foo{
    public String foo();
}

public class A implements Foo {
    public String foo() {
        return "A said foo";
    }
}

public class B implements Foo{
    public String foo() {
        return "B said foo";
    }
}

public class Template<T extends Foo> {
    private T mT;

    public Template(T t) {
        mT = t;
    }
    public String bar() {
        return mT.foo();
    }
}

You could probably just make a class ABAbstract as a parent type for A and B. You can use this class as the argument then, or stay with Wildcard Generics and cast it to ABAbstract. You could also let both classes A and B implement an interface declaring the method foo. This would be probably be the easiest way to make your compile don't throw any errors and goes exactly with what you said "you were looking for".

But I thinky ou have to write:

public class Template<T extends ABInterface> {

but i am not definately sure about this. It could also be implemenet altouth the classes need to use the keyword implement.

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