简体   繁体   English

根据Java中的子类Type定义泛型类父类方法

[英]Define generic Type of parent class method depending on subclass Type in Java

Is it possible to dynamically identify T as a return type depending on subclass Type? 是否可以根据子类类型动态识别T作为返回类型? 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 . 它在Java类型系统是不可能的Parent指确切的类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. 但是,它可以有一个类型参数(比如T ),子类可以指定,或者自己,或者其他类型(无论他们想要什么),并使用抽象方法将获取该类型T的实例的任务委托给子类。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM