Home >Java >javaTutorial >Can Type Variables Refer to Their Defining Class in Java?

Can Type Variables Refer to Their Defining Class in Java?

DDD
DDDOriginal
2024-12-24 15:27:15961browse

Can Type Variables Refer to Their Defining Class in Java?

Can Type Variables Refer to the Current Type?

Suppose you want to create a function that returns an instance of the current type. Is there a way to ensure that T refers specifically to the subtype (e.g., T should refer to B in class B)?

Implementing the Solution

Extending StriplingWarrior's response, the following pattern is essential for achieving this (a recipe for a hierarchical fluent builder API):

SOLUTION

  1. Define a Base Abstract Class or Interface:

    Establish a contract for obtaining the runtime type of an instance extending the class:

    abstract class SelfTyped<SELF extends SelfTyped<SELF>> {
       abstract SELF self();
    }
  2. Create Intermediate Abstract Classes:

    Intermediate classes maintain the recursive type parameter SELF. They should be abstract to prevent direct use:

    public abstract class MyBaseClass<SELF extends MyBaseClass<SELF>> extends SelfTyped<SELF> {...}
  3. Define Leaf Classes:

    The final classes resolve the SELF type parameter with their own type. Make them final for safety:

    public final class MyLeafClass extends MyBaseClass<MyLeafClass> {...}

Example Usage:

MyLeafClass mlc = new MyLeafClass().baseMethod().leafMethod();
AnotherLeafClass alc = new AnotherLeafClass().baseMethod().anotherLeafMethod();

Caution and Conclusion

This pattern is an implementation of the "curiously recurring template" in Java. While powerful, it requires careful use and is best reserved for internal APIs only. The pattern is inherently unsafe and must be used with caution to avoid misuse. However, when employed effectively, it can enhance the expressiveness and usability of builder APIs.

The above is the detailed content of Can Type Variables Refer to Their Defining Class in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn