[英]Can I have a method argument typed “this class”?
I want to have an argument of type "this class" in an interface's method signature, so that any class, for example MyClass
, implementing it will have that method with an argument of type MyClass
. 我希望在接口的方法签名中有一个类型为“this class”的参数,因此任何实现它的类(例如MyClass
)都将使用类型为MyClass
的参数。
public interface MyInterface {
public thisClass myMethod(thisClass other);
...
}
public class MyClass implements MyInterface {
// has to reference this class in the implementation
public MyClass myMethod(MyClass other){
...
}
}
Is this possible, or should I just bind the argument with the interface and have each implementation check for it?
这是可能的,还是我应该将参数与接口绑定并让每个实现检查它?
public interface MyInterface<T> {
public T myMethod(T other);
...
}
public class MyClass implements MyInterface<MyClass> {
// has to reference this class in the implementation
public MyClass myMethod(MyClass other){
...
}
}
This somewhat enforces that T is the class that implements the interface: 这有点强制T是实现接口的类:
public interface MyInterface<T extends MyInterface<T>> {
public T myMethod(T other);
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.