我在一个程序中遇到接口的问题.我想创建一个接口,它有一个方法接收/返回对自己对象的类型的引用.这是一样的:
public interface I {
? getSelf();
}
public class A implements I {
A getSelf() {
return this;
}
}
public class B implements I {
B getSelf() {
return this;
}
}
我不能使用“I”,它是一个“?”,因为我不想返回对接口的引用,而是类.我搜索并发现在Java中没有办法“自我引用”,所以我不能只是用“?在“self”关键字或类似这样的示例中.其实我想出了一个解决方案
public interface I<SELF> {
SELF getSelf();
}
public class A implements I<A> {
A getSelf() {
return this;
}
}
public class B implements I<B> {
B getSelf() {
return this;
}
}
但它似乎似乎是一种解决方法或类似的东西.有另一种方法吗?
解决方法
在扩展接口时,有一种强制使用自己的类作为参数的方法:
interface I<SELF extends I<SELF>> {
SELF getSelf();
}
class A implements I<A> {
A getSelf() {
return this;
}
}
class B implements I<A> { // illegal: Bound mismatch
A getSelf() {
return this;
}
}
这甚至在编写泛型类时起作用.只有一个缺点:一个人必须把它抛给自己.
正如安德烈·马卡罗夫(Andrey Makarov
class A<SELF extends A<SELF>> {
SELF getSelf() {
return (SELF)this;
}
}
class C extends A<B> {} // Does not fail.
// C myC = new C();
// B myB = myC.getSelf(); // <-- ClassCastException