Q:

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:

check for type and cast to A or B.
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".

A:

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. 

A:

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

