Pregunta

Is it possible to dynamically identify T as a return type depending on subclass Type? I want something like the following:

public class Parent {
        public <T extends Parent> T foo() {
                return (T)this;
        }
}

public class Child extends Parent {
        public void childMethod() {
                System.out.println("childMethod called");
        }
}

And then to call:

Child child = new Child();
child.foo().childMethod();

Without defining the type like so:

Child child = new Child();
child.foo().<Child>childMethod(); // compiles fine

Thanks in advance!

¿Fue útil?

Solución

You want this:

public class Parent<T extends Parent<T>> {
    public T foo() {
        return (T)this;
    }
}

public class Child extends Parent<Child> {
    public void childMethod() {
        System.out.println("childMethod called");
    }
}

Child child = new Child();
child.foo().childMethod(); // compiles

Otros consejos

It is impossible in the Java type system for Parent to refer to the exact class of this. However, it can have a type parameter (say T) that subclasses can specify, as either themselves, or some other type (whatever they want), and use an abstract method to delegate the task of obtaining an instance of a that type T to the subclass.

public abstract class Parent<T> {
    // the implementer is responsible for how to get an instance of T
    public abstract T getT();
    // in this case, foo() is kind of redundant
    public T foo() {
        return getT();
    }
}

public class Child extends Parent<Child> {
    public Child getT() {
        return this;
    }
    public void childMethod() {
        System.out.println("childMethod called");
    }
}

Child child = new Child();
child.foo().childMethod(); // compiles
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top