Is there a way to refer to the current type with a type variable?

后端 未结 7 1809
悲&欢浪女
悲&欢浪女 2020-11-22 03:01

Suppose I\'m trying to write a function to return an instance of the current type. Is there a way to make T refer to the exact subtype (so T should

7条回答
  •  悲&欢浪女
    2020-11-22 04:01

    I found a way do this, it's sort of silly but it works:

    In the top level class (A):

    protected final  T a(T type) {
            return type
    }
    

    Assuming C extends B and B extends A.

    Invoking:

    C c = new C();
    //Any order is fine and you have compile time safety and IDE assistance.
    c.setA("a").a(c).setB("b").a(c).setC("c");
    

提交回复
热议问题