Master Java Reflection with the Reflector Library: Real‑World Examples
This article introduces the Reflector library—a comprehensive Java reflection utility—covers its core features, shows how to download it from GitHub, and provides step‑by‑step code examples for accessing private fields, invoking methods, creating instances, handling annotations, copying objects, and more, all with expected output.
Introduction
Reflection is a core feature of the Java language that allows a program to inspect and manipulate class metadata—such as fields, methods, constructors, and annotations—at runtime. It is widely used in frameworks, dynamic proxies, serialization, and debugging, but over‑use can introduce performance overhead and security concerns.
Reflector library
Reflector is a Java library that simplifies the use of the Reflection API while keeping the operations efficient. The library is compatible with Java 21 and can be obtained from the public repository:
https://github.com/alxkm/reflector
Key utility classes
AnnotationUtils – helper methods for reading and processing annotations on classes, methods and fields.
ClassBasicUtils – basic operations for class metadata.
ConstructorUtils – convenient access to constructor information.
FieldsExtraUtils – extended field utilities (e.g., retrieving private or annotated fields).
FieldUtils – common field‑related operations.
GeneralUtils – miscellaneous helper methods.
InvokeUtils – simplified method invocation on objects or classes.
MethodEnhancementsUtils – additional method‑related features.
MethodUtils – utilities for method lookup and invocation.
MiscellaneousUtils – assorted utility methods.
ObjectUtils – object copying, comparison and related helpers.
PackageUtils – class scanning and package handling.
ReflectionUtils – the core set of reflection tools.
ReflectionUtilsLegacy – legacy compatibility utilities.
SecurityUtils – utilities that help perform reflection safely.
Practical usage examples
1. Retrieve private fields and methods
List<Field> fields = ReflectionUtils.getAllPrivateFields(User.class);
fields.forEach(System.out::println);
List<Method> methods = ReflectionUtils.getAllPrivateMethods(User.class);
methods.forEach(System.err::println);Sample output:
private java.lang.Long com.pack.User.id
private java.lang.String com.pack.User.name
private java.lang.Integer com.pack.User.age
private void com.pack.User.work()2. Retrieve public and protected methods
List<Method> methods = ReflectionUtils.getAllPublicProtectedMethods(User.class);
methods.forEach(System.err::println);3. Dynamically create an instance
String className = "com.pack.reflector.test.User";
Object[] params = {1L, "pack_xg", 33};
User instance = (User) ReflectionUtils.invokeInstance(className, params);
System.err.println(instance);Output:
User[id=1, name=pack_xg, age=33]4. Find a method by name and list default interface methods
Method method = ReflectionUtils.findMethodByName(User.class, "getId");
System.err.println(method);
List<Method> defaultMethods = ReflectionUtils.getDefaultMethodsOfInterfaces(User.class);
defaultMethods.forEach(System.out::println);Output:
public java.lang.Long com.pack.User.getId()
public default java.lang.Object com.pack.DAO.create(java.lang.Object)5. Retrieve fields annotated with a specific annotation
List<Field> fields = ReflectionUtils.getAllAnnotatedFields(User.class, Pack.class);
fields.forEach(System.out::println);Output:
private java.lang.String com.pack.User.name
private java.lang.Integer com.pack.User.age6. Get field modifiers
int modifiers = ReflectionUtils.getFieldModifiers(User.class, "MSG");
System.err.println(Modifier.toString(modifiers));Output:
public static final7. Invoke a method on an object
User user = new User(1L, "Pack_xg", 33);
ReflectionUtils.invokeMethod(user, "setName",
new Class[]{String.class}, new Object[]{"Pack"});
System.err.println(user);Output:
User[id=1, name=Pack, age=33]8. Deep copy an object
User user = new User(1L, "Pack_xg", 33);
User copyUser = (User) ReflectionUtils.copy(user);The copy is performed by recursively reflecting over each field; final fields are skipped.
9. Additional utilities
Check whether a field is of a primitive type: ReflectionUtils.isFieldPrimitiveType(field). Spring’s BeanUtils.isSimpleProperty(Class<?> type) can be used as an alternative.
Obtain the runtime types of arguments passed to a var‑args method:
Class<?>[] argTypes = ReflectionUtils.getArrayValuesTypesByArgs(new Object[]{"xxx", 42, 666L});Get the component type of an array:
Class<?> component = ReflectionUtils.getArrayComponentType(users.getClass());Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
