带有extends关键字的Java构造函数

时间:2016-10-28 14:04:42

标签: java constructor

我有一个看起来像这样的java类:

public class thisThing {

    private final Class<? extends anInterface> member;

    public thisThing(Class<? extends anInterface> member) {
        this.member = member;
    }
}

我的问题是:如何调用thisThing构造函数?

2 个答案:

答案 0 :(得分:3)

为了调用thisThing的构造函数,您需要首先定义一个实现anInterface的类:

class ClassForThisThing implements anInterface {
    ... // interface methods go here
}

现在您可以按如下方式实例化thisThing

thisThing theThing = new thisThing(ClassForThisThing.class);

这种实例化背后的想法通常是给thisThing一个类,它可以通过反射创建anInterface的实例。编译器确保传递给构造函数的类与anInterface兼容,确保像这样的强制转换

anInterface memberInstance = (anInterface)member.newInstance();

总是在运行时成功。

答案 1 :(得分:1)

我不喜欢你做过的事。

为什么不呢?这里不需要泛型。你只是在做作文。传入任何实现AnInterface的引用。 Liskov替代原则说一切都会正常。

public class ThisThing {

    private AnInterface member;

    public ThisThing(AnInterface member) {
        this.member = member;
    }
}

这是界面:

public interface AnInterface {
    void doSomething();
}

这是一个实现:

public class Demo implements AnInterface {
    public void doSomething() { System.out.println("Did it"); }
}
相关问题