如何引用接口在 Java 中实现的类类型? [英] How can I refer to the class type a interface is implementing in Java?

查看:24
本文介绍了如何引用接口在 Java 中实现的类类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在制作的程序中遇到了接口问题.我想创建一个接口,它有一个方法接收/返回对自己对象类型的引用.它是这样的:

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",因为我不想返回对接口的引用,而是返回类.我搜索并发现在 Java 中没有办法自我引用",所以我不能只替换那个?"在self"关键字或类似内容的示例中.实际上,我想出了一个类似的解决方案

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 转换为 SELF.

This even works when writing generic classes. Only drawback: one has to cast this to SELF.

正如 Andrey Makarov 在 下面的评论 这在编写泛型类时不能可靠地工作.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆