Vlad
Vlad

Reputation: 1680

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".

Upvotes: 1

Views: 137

Answers (3)

dogbane
dogbane

Reputation: 274888

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

Upvotes: 4

The Surrican
The Surrican

Reputation: 29874

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.

Upvotes: 0

Mirek Pluta
Mirek Pluta

Reputation: 8033

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.

Upvotes: 5

Related Questions