加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 05:48:09 所属栏目:Java 来源:网络整理
导读:我在一个程序中遇到接口的问题.我想创建一个接口,它有一个方法接收/返回对自己对象的类型的引用.这是一样的: public interface I { ? getSelf();}public class A implements I { A getSelf() { return this; }}public class B implements I { B getSelf() {
我在一个程序中遇到接口的问题.我想创建一个接口,它有一个方法接收/返回对自己对象的类型的引用.这是一样的:
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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读