简体   繁体   English

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

[英]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.

相关问题 我可以通过基类类型的引用访问子类方法吗? - Can I access a subclass method through a base class-typed reference? 为什么执行方法不能有参数 - Why can't an implementing method have an argument 为什么我在Java中的同一个类中没有抽象和静态方法 - Why can I not have an abstract and static method in the same class in Java 我可以在没有映射到数据库的实体 class 中有一个方法吗 - can i have a method in entity class without Mapping to the database 我怎样才能有一个接受“my type”类型参数的抽象方法? - How can I have an abstract method that accepts an argument of type “my type”? 如果我已将其声明为Java中类的成员变量,是否可以访问另一个方法中一个方法的变量值? - Can i access the value of a variable of one method in another method if i have declared it as a member variable of the class in java? parameter.method 或 argument.method 怎么可能? 我以为它总是 class.method。 有人可以解释吗? - How is parameter.method or argument.method possible? I thought it was always class.method. Can someone explain? 如何编写以片段类作为参数的方法,使我可以创建该片段的新实例? - How can I write a method with a fragment class as an argument that will allow me to create a new instance of that fragment? 如何从参数化类型方法参数中获取参数化类型类? - How can I get the parameterized-type class from a parameterized-type method argument? 为什么我可以对没有stream()方法的类的对象调用stream()方法? - Why can I call the stream() method on objects of a class that don't have the stream()-method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM