我有一个Java类,看起来像这样:Java的构造与extends关键字
public class thisThing {
private final Class<? extends anInterface> member;
public thisThing(Class<? extends anInterface> member) {
this.member = member;
}
}
我的问题是:我怎么叫thisThing
构造?
我有一个Java类,看起来像这样:Java的构造与extends关键字
public class thisThing {
private final Class<? extends anInterface> member;
public thisThing(Class<? extends anInterface> member) {
this.member = member;
}
}
我的问题是:我怎么叫thisThing
构造?
为了调用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();
总是在运行时取得成功。
我不喜欢你所做的。
为什么不是这样?这里不需要泛型。你只是在做作文。通过实施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"); }
}
我可能不理解你的问题,但并不需要简单地调用新thisThing()和作为参数传递任何实现anInterface的对象? – facundop
了解Java编码标准:应该是ThisThing – duffymo
您只需将它传递给一个实现接口的类即可... – Li357