[英]Java, force implementation of method without knowing parameters
I have an abstract class that performs basic operations, now I want to force every derived class to have a method "check", but the point is I know nothing about this method. 我有一个执行基本操作的抽象类,现在我想强制每个派生类都使用“检查”方法,但要点是我对该方法一无所知。 For example, the abstract class:
例如,抽象类:
public abstract class Service<T extends Transport> {
public T getTransport(int id) {
[...]
}
public abstract boolean checkTransport(T transport, ...);
}
and two implementing classes: 和两个实现类:
public ServiceAAA extends Service<ClassA> {
public boolean checkTransport(ClassA t) {
[...]
}
}
public ServiceBBB extends Service<ClassB> {
public boolean checkTransport(ClassB t, Integer value, Integer otherValue) {
[...]
}
}
The ServiceBBB needs two parameter to check the object t of class ClassB. ServiceBBB需要两个参数来检查类ClassB的对象t。 Of course it's not working, is there a way to force the subclass to implement the checkTransport method without using the "Object ... " notation?
当然这是行不通的,有没有一种方法可以强制子类在不使用“ Object ...”表示法的情况下实现checkTransport方法?
No, there isn't. 不,没有。
Let's pretend there were a way. 让我们假设有一个办法。 How would you invoke this method, either from the abstract Service class, or from any call site that had a reference to this object typed as
Service<...>
? 您如何从抽象的Service类或任何引用了此对象类型为
Service<...>
调用站点调用此方法? There'd be no way of knowing what the specific subclass's method expects, and thus no way of invoking the method. 没有办法知道特定子类的方法的期望,因此也就没有办法调用该方法。
One way around this is to pass the checker in as a class to Service; 解决此问题的一种方法是将检查程序作为类传递给Service。 that is, to use composition instead of inheritance.
也就是说,使用合成代替继承。 If you do that, you can have the checker's interface take no extra arguments at all (a
Predicate
might work, for instance), and the specific subclasses that implement that checker could have the arguments passed at construction time. 如果这样做,则可以使检查器的界面根本不接受任何额外的参数(例如,
Predicate
可能起作用),并且实现该检查器的特定子类可以在构造时传递参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.