Conceptions
Traditional reflection can often lead to verbose code. For instance, setAccessible(true) is a kind of regular code snippet. In com.alioth4j.reflect library, I encapsulate the regular usage of reflection API to simplify the processes of object creation and method invocation.
Meanwhile, drawing inspiration from the Builder pattern, I reimagine the way to use reflection: method chaining. This approach enchances code readability and mainainability.
Step-by-Step Usage
Step 1: Instantiate
| |
or
| |
or
| |
or
| |
Step 2: Invoke methods
| |
Step 3: Get the instance
| |
An Usage Example
| |
Implementation
public class Reflect<I>
Generics
Use <I> to improve type safety.
Fields
Two fields:
| |
Constructors
Constructor is (part of) the instantiation step. Just fill in the fields.
Methods
- Encapsulate the reflection API inside.
- Return
thisobject to support method chaining.
public class ReflectException
- Thrown when an exception occurs during the usage of
com.alioth4j.reflect.Reflect - It is an encapsulation of the reflection-related exceptions, providing an unified way to handle exceptions
- As reflection is an unsafe mechanism itself, the safety should be guaranteed by the user
Conclusion
With the elegance of the Builder pattern, this library offers developers a simpler and cleaner way to leverage reflection in Java applications.