2

我有这个界面,

public interface IAnything {
  void m1();
  void m3();
}

还有两个实现这个接口的抽象类:

public abstract class AbstractThing1 implements IAnything {
  public void m1() {}
  public void m3() {}
}

public abstract class AbstractThing2 implements IAnything {
  public void m1() {}
  public void m3() {}
}

在我的代码中的某个地方,我想调用 a function doSomething(kindOfAbstractClass)that perfoms m1()and m3(),以及其他取决于 kindOfAbstractClass 的工作。

我该如何定义和调用doSomething()?我这样做了,但它不起作用。谢谢

private <T extends IAnything> void doSomething(T kindOfAbstractClass) {
...
kindOfAbstractClass.m1();
kindOfAbstractClass.m3();
...
}

doSomething(AbstractThing1.class);
4

2 回答 2

3

你的问题是你提供一个类类型而不是一个实例作为参数给 doSomething

看看下面的修改代码:

public class MyClass {


    void doIt(){
        doSomething(new ConcreteThing());       
    }

    private <T extends IAnything> void doSomething(T kindOfAbstractClass) {

            kindOfAbstractClass.m1();
            kindOfAbstractClass.m3();
    }

}


interface IAnything {
      void m1();
      void m3();
}

abstract class AbstractThing1 implements IAnything {
      public void m1() {}
      public void m3() {}
}


class ConcreteThing extends AbstractThing1{

}
于 2013-02-14T13:28:27.443 回答
3

尝试这个:

private void doSomething(IAnything  kindOfAbstractClass) {
...
kindOfAbstractClass.m1();
kindOfAbstractClass.m3();
...
}
于 2013-02-14T13:22:27.403 回答