如何引用接口在 Java 中实现的类类型?

编程入门 行业动态 更新时间:2024-10-24 07:28:58
本文介绍了如何引用接口在 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屋!

更多推荐

[db:关键词]

本文发布于:2023-03-28 19:15:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/736988.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:接口   类型   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!