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!
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.