我可以将方法参数键入“此类”吗?

时间:2010-08-28 02:56:25

标签: java method-signature

我希望在接口的方法签名中有一个类型为“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){
        ...
    }
}
这是可能的,还是我应该将参数与接口绑定并让每个实现检查它?

2 个答案:

答案 0 :(得分:3)

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){
      ...
   } 
}

答案 1 :(得分:3)

这有点强制T是实现接口的类:

public interface MyInterface<T extends MyInterface<T>> {
   public T myMethod(T other);
   ...
}