1

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

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Indeed. Without the interface (or superclass), the only way to do this would be via reflection, generics or no.
4

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

1 Comment

I am not a creator of A and B classes.
0

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.

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.