In Java, it is not possible to directly refer to the current type with a type variable. The issue arises when trying to write methods that can return an instance of the current type, which becomes problematic when dealing with subtyping. For instance, declaring a generic method with return type T in a base class will refer to the base class type in subclasses, not the actual subclass type.
To address this, a recursive bound and an abstract class hierarchy can be employed as follows:
abstract class SelfTyped<SELF extends SelfTyped<SELF>> { abstract SELF self(); } class MyBaseClass<SELF extends MyBaseClass<SELF>> extends SelfTyped<SELF> { MyBaseClass() { } public SELF baseMethod() { return self(); } } final class MyLeafClass extends MyBaseClass<MyLeafClass> { @Override MyLeafClass self() { return this; } public MyLeafClass leafMethod() { return self(); } }
In this approach, leaf classes resolve the recursive type parameter SELF to their own type and implement self(). Leaf classes can be used directly, allowing method chaining while preserving the correct return type:
MyLeafClass mlc = new MyLeafClass().baseMethod().leafMethod(); AnotherLeafClass alc = new AnotherLeafClass().baseMethod().anotherLeafMethod();
Caution: This technique relies on the curiously recurring template pattern (CRT) and introduces certain risks:
To mitigate these risks, ensure that involved classes are not publicly extendable and consider using package-private constructors and methods for SelfTyped and self().
While this workaround provides a means of referencing the current type, it introduces additional complexity and limitations. It is advised to carefully weigh the benefits against potential drawbacks before implementing it. In cases where explicit type referencing is crucial, this solution can be useful, but avoid relying on it excessively or in public APIs.
The above is the detailed content of How Can I Refer to the Current Type with a Type Variable in Java?. For more information, please follow other related articles on the PHP Chinese website!