在接口中使用Java泛型来强制执行实现类型作为参数的方法 [英] Using Java generics in an interface to enforce implementation of a method with the implementing type as a parameter
问题描述
我有这样的界面:
public interface DataObject {
...
public void copyFrom(DataObject source);
...
}
以及一个实现它的类: p>
public class DataObjectImpl implements DataObject {
...
@Override
public void copyFrom(final DataObject source){...}
$ b public void copyFrom(final DataObjectImpl source){...}
...
}
有没有什么办法可以强制在DataObject接口中使用泛型实现一个public void copyFrom(DataObjectImpl source)方法如果你只是需要处理 copyFrom
,那么不同的情况下,如果 DataObject
它给出的是与对象本身相同的类型,只是做这样的事情:
public class DataObjectImpl implements DataObject {
public void copyFrom(final DataObject source){
if(source instanceof DataObjectImpl){
...
}
els e {
...
}
}
}
另一方面,你可以像这样做,对于采用实现类型的方法使用不同的名称。但是,我不认为它有什么好处。
public interface DataObject< T extends DataObject< T>> {
public void copyFrom(DataObject source);
public void copyFromImpl(T source);
}
public class DataObjectImpl implements DataObject< DataObjectImpl> {
public void copyFrom(final DataObject source){...}
public void copyFromImpl(final DataObjectImpl source){...}
}
I have an interface like this:
public interface DataObject {
...
public void copyFrom(DataObject source);
...
}
And a class that implements it:
public class DataObjectImpl implements DataObject {
...
@Override
public void copyFrom(final DataObject source) {...}
public void copyFrom(final DataObjectImpl source) {...}
...
}
Is there any way that I can enforce the implementation of a "public void copyFrom(DataObjectImpl source)" method in the DataObject interface, using generics or otherwise?
If you just need to handle copyFrom
differently if the DataObject
it's given is the same type as the object itself, just do something like this:
public class DataObjectImpl implements DataObject {
public void copyFrom(final DataObject source) {
if (source instanceof DataObjectImpl) {
...
}
else {
...
}
}
}
On the other hand, you could do it like this, using a different name for the method taking an implementation type. However, I don't see what good this does.
public interface DataObject<T extends DataObject<T>> {
public void copyFrom(DataObject source);
public void copyFromImpl(T source);
}
public class DataObjectImpl implements DataObject<DataObjectImpl> {
public void copyFrom(final DataObject source) { ... }
public void copyFromImpl(final DataObjectImpl source) { ... }
}
这篇关于在接口中使用Java泛型来强制执行实现类型作为参数的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!