我怎样才能引用一个接口在Java中实现的类类型? [英] How can I refer to the class type a interface is implementing in Java?
问题描述
我遇到了一个我正在编写的程序中的接口问题。我想创建一个接口,它的方法之一是接收/返回对自己对象类型的引用。它是这样的:
public interface I {
? getSelf();
}
public class A implements I {
getSelf(){
return this;
public class B implements I {
B getSelf(){
return this;
我不能使用I一个?,因为我不想返回一个对接口的引用,而是类。我搜索了一下,发现在Java中没有办法自我引用,所以我不能用这个?替代。在自我关键字或类似的例子中。实际上,我想出了一个解决方案,就像
public interface I< SELF> {
SELF getSelf();
}
public class A实现了I< A> {
getSelf(){
return this;
}
}
公共类B实现了I< B> {
B getSelf(){
return this;
}
}
但它看起来像是一种解决方法或类似的方法。有没有另外一种方法可以做到这一点?
扩展接口时有一种强制使用自己的类作为参数的方法:
interface I< SELF extends I< SELF>> {
SELF getSelf();
}
class A实现了I< A> {
getSelf(){
return this;
}
}
class B实现了I< A> {//非法:绑定不匹配
getSelf(){
return this;
这在编写泛型类时甚至可以工作。只有缺点:必须将这个
转换为 SELF
。
正如Andrey Makarov在不是可靠地工作。
class A< SELF extends A< SELF>> {
SELF getSelf(){
return(SELF)this;
}
}
class C extends A< B> {} //不会失败。
// C myC = new C();
// B myB = myC.getSelf(); //< - ClassCastException
I came to a problem with interfaces in a program I'm making. I want to create a interface which have one of its methods receiving/returning a reference to the type of the own object. It was something like:
public interface I {
? getSelf();
}
public class A implements I {
A getSelf() {
return this;
}
}
public class B implements I {
B getSelf() {
return this;
}
}
I can't use an "I" where it's a "?", because I don't want to return a reference to the interface, but the class. I searched and found that there are no way to "self-refer" in Java, so I can't just substitute that "?" in the example for a "self" keyword or something like this. Actually, I came up to a solution that goes like
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;
}
}
But it really seems like a workaround or something alike. Is there another way to do so?
解决方案 There is a way to enforce using ones own class as a parameter when extending an interface:
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;
}
}
This even works when writing generic classes. Only drawback: one has to cast this
to SELF
.
As Andrey Makarov noted in a comment below this does not work reliably when writing generic classes.
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
这篇关于我怎样才能引用一个接口在Java中实现的类类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!