How do I reference a class type whose interface is implemented in Java?

I encountered an interface problem in a program I want to create an interface that has a method that receives / returns a reference to the type of its own object This is the same:

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 "I", it's a "?", Because I don't want to return a reference to an interface, but a class I searched and found that there is no way to "self reference" in Java, so I can't just use "? In the" self "keyword or similar examples Actually, I came up with a solution

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 seems to be a solution or something like that Is there another way?

Solution

When extending an interface, there is a method to force its own class as a parameter:

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 There is only one drawback: one must throw it to himself

As 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
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>