在泛型类中调用方法

时间:2012-09-30 16:41:32

标签: java generics

假设我们有两个类A,B:

class A extends SomeClass {
   public String getProp() {
      return "propA";
   }
}

class B extends SomeOtherClass{
   private String propB;

   public B setProp(String value) {
      propB = value;
      return this;
   }

   public String getProp() {
      return propB;
   }
}

并且假设我们有另一个名为X的类,并且这个类X有一个方法someMethod,它接受任何这些类的引用,有没有一种方法可以在这个方法中使用泛型来调用getProp()根据已经通过的对象?

4 个答案:

答案 0 :(得分:2)

不使用泛型。

您可以为具有getProp()方法的这些类定义公共接口。然后使用它的方法应该接受接口的一个实例,并且可以在接口上调用getProp()方法,该方法将由您传入的具体类实现。

答案 1 :(得分:0)

泛型在编译时用于类型安全,而不是在运行时实现多态。所以我不认为你问的是可能的。

在您的方案中,您应该考虑创建一个界面。像这样:

public interface PropInf{
  String getProp();
}

然后,您必须在两个类中实现此接口。使用此接口的引用变量,您可以实现多态性。

答案 2 :(得分:0)

按如下方式定义interface

interface StringPropProvider {
  String getProp();
}

然后将您的类定义为实现该接口:

class A extends SomeClass implements StringPropProvider {
   public String getProp() {
    return "propA";
}

class B extends SomeOtherClass implements StringPropProvider {
  private String propB;

  public B setProp(String value) {
    propB = value;
    return this;
  }

  public String getProp() {
    return propB;
  }
}

答案 3 :(得分:0)

这可以算是一个答案,但我不喜欢它..

public class X<T>{
public void someMethod(T t) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
    t.getClass().getMethod("getProp", null).invoke(t, null);
}
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    X<A> weird = new X<>();
    A a = new A();
    weird.someMethod(a);
}

}

相关问题