Package io.github.connellite.reflection
Class ReflectionUtil
java.lang.Object
io.github.connellite.reflection.ReflectionUtil
Small helpers around
Field, Method, and Constructor: accessibility,
lookup by name or annotation, and getInstance shortcuts. Prefer
getInstance(Class, Class[], Object...) when the constructor takes null arguments
or parameter types must be wider than the runtime types of initargs.-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic <T> TcastFieldValue(Class<T> type, Object value) Casts a reflected field value totypewith primitive-aware behavior.static booleandeclaresException(Method method, Class<?> exceptionType) trueifmethoddeclaresexceptionTypeor a supertype of it.static FieldfindDeclaredField(Class<?> type, String name) Field namednameontypeor a superclass, made accessible, ornull.static FieldfindDeclaredField(Class<?> type, String name, Class<?> fieldType) Field namednamewith exactfieldTypeontypeor a superclass, made accessible, ornull.static MethodfindMethod(Class<?> type, String name, int paramCount) Method namednamewithparamCountparameters ontype, a superclass, or an implemented interface (most specific class first).static MethodfindMethod(Class<?> type, String name, Class<?>... paramTypes) Method namednamewith the given parameter types ontype, a superclass, or an implemented interface (most specific class first).static <T> TReads an instance field declared onclazz(not a subclass), for example a field on a superclass whenclazzis that superclass.static <T> TReads a field declared ono's runtime class.getAllDeclaredFields(Class<?> type) Declared fields fromtypeand its superclasses, superclass first, excludingObject.getAllDeclaredMethods(Class<?> type) Declared methods fromtypeand its superclasses, superclass first, excludingObject.Shortcut overload forgetAllGenericParameterClasses(Type)using a reflected field.getAllGenericParameterClasses(Type genericType) Extracts all generic argument classes from aType.getAllInterfaces(Class<?> cls) Collects every interface type implemented (directly or indirectly) bycls: interfaces declared oncls, super-interfaces of those, and the same closure for each superclass up toObject.getAllMethodsByAnnotation(Class<?> entity, Class<? extends Annotation> clazz) Returns all declared methods that carry the given annotation (possibly empty).static <A extends Annotation>
AgetClassOrModuleAnnotation(Class<?> clazz, Class<A> annotation) static <A extends Annotation>
AgetClassOrPackageAnnotation(Class<?> clazz, Class<A> annotation) static <T> Constructor<T>getConstructor(Class<T> t) No-argument declared constructor, made accessible.static <T> Constructor<T>getConstructor(Class<T> t, Class<?>... parameterTypes) Declared constructor with the given parameter types, made accessible.getEnumMap(Class<E> enumClass) Builds a map from each enum constant's name to that constant.getEnumMap(Class<E> enumClass, Function<? super E, ? extends K> keyExtractor) Builds a map from a derived key (per constant) to the enum constant, for example a numerictypefield exposed by a getter.getGenericInterfaceParameterClasses(Class<?> type, Class<?> rawInterface) Generic arguments of the firstrawInterfaceparameterization found ontypeor its superclasses.static <T> TgetInstance(Class<T> t) getConstructor(type).newInstance()— no-arg instance.static <T> TgetInstance(Class<T> t, Class<?>[] parameterTypes, Object... initargs) Invokest.getDeclaredConstructor(parameterTypes).newInstance(initargs)with access opened.static <T> TgetInstance(Class<T> t, Object... initargs) Resolves a constructor from the runtime classes ofinitargs(with primitive wrapper unboxing for matchingint,boolean, etc.).static MethodgetMethodByAnnotation(Class<?> entity, Class<? extends Annotation> clazz) Returns the first declared method annotated withclazz, ornull.static MethodgetMethodByName(Class<?> entity, String nameMethod) static <T> TReads a public field (including inherited) viaClass.getField(String).static <T> TReads a static field and casts it totype.static <T> TReads a field declared on the direct superclass ofo's class.static ObjectgetValueField(Object obj, Field field) Reads a field value, callingAccessibleObject.trySetAccessible()whenAccessibleObject.canAccess(Object)is false (private, protected, package-private from another package, etc.).static booleanhasClassOrModuleAnnotation(Class<?> clazz, Class<? extends Annotation> annotation) WhethergetClassOrModuleAnnotation(Class, Class)finds the annotation.static booleanhasClassOrPackageAnnotation(Class<?> clazz, Class<? extends Annotation> annotation) WhethergetClassOrPackageAnnotation(Class, Class)finds the annotation.static ObjectInvokes an instance method with no parameters ono's runtime class.static Objectstatic ObjectinvokeDefault(Object proxy, Method method, Object... args) Invokes an interfacedefaultmethod onproxy.static ObjectinvokeStatic(Class<?> clazz, String method) Invokes a static method with no parameters.static booleanisEqualsMethod(Method method) trueifmethodisequals(Object).static booleanisHashCodeMethod(Method method) trueifmethodishashCode()with no parameters.static booleanisInnerClass(Class<?> cls) Returns whetherclsis a nested type with a lexically enclosing class, i.e.static booleanisObjectMethod(Method method) static booleanisToStringMethod(Method method) trueifmethodistoString()with no parameters.static Class<?>Class of the code that called this method — shorthand forMethodHandles.lookup().lookupClass()at the call site.static voidopen(AccessibleObject member) Opensmemberfor reflective access.static Class<?>primitiveToWrapper(Class<?> primitive) Maps a primitive type token to its wrapper type; non-primitive inputs are returned unchanged.static <X extends Throwable>
voidRethrowstas-is, including checked exceptions, without wrapping.static <T> Constructor<T>resolveRecordConstructor(Class<T> recordClass) Resolves canonical constructor of a record class and makes it accessible.static TyperesolveTypeArgument(Class<?> type, Class<?> target, int index) Resolves type argumentindexoftargetas implemented bytype, substituting interface type variables along the way.static voidWrites a field declared ono's runtime class.static voidWrites a static field.static voidsetValueField(Object obj, Field field, Object value) Writes a field value, callingAccessibleObject.trySetAccessible()whenAccessibleObject.canAccess(Object)is false.static Class<?>unwrapProxy(Class<?> type) User class behind a JDK, CGLIB, Byte Buddy, Hibernate, Mockito, or Javassist proxy.
-
Constructor Details
-
ReflectionUtil
public ReflectionUtil()
-
-
Method Details
-
lookupClass
Class of the code that called this method — shorthand forMethodHandles.lookup().lookupClass()at the call site. -
invokeStatic
public static Object invokeStatic(Class<?> clazz, String method) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException Invokes a static method with no parameters.- Parameters:
clazz- class declaring the methodmethod- method name- Returns:
- the invocation result (possibly
null) - Throws:
NoSuchMethodExceptionInvocationTargetExceptionIllegalAccessException
-
invoke
public static Object invoke(Object o, String method) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException Invokes an instance method with no parameters ono's runtime class. -
invoke
public static Object invoke(Method method, Object target, Object... args) throws InvocationTargetException, IllegalAccessException -
invokeDefault
Invokes an interfacedefaultmethod onproxy.- Throws:
Throwable
-
getStatic
public static <T> T getStatic(Class<?> clazz, String f, Class<T> type) throws NoSuchFieldException, IllegalAccessException Reads a static field and casts it totype. -
setStatic
public static void setStatic(Class<?> clazz, String f, Object value) throws NoSuchFieldException, IllegalAccessException Writes a static field. -
getSuper
public static <T> T getSuper(Object o, String f, Class<T> type) throws NoSuchFieldException, IllegalAccessException Reads a field declared on the direct superclass ofo's class. -
get
public static <T> T get(Object instance, Class<?> clazz, String f, Class<T> type) throws NoSuchFieldException, IllegalAccessException Reads an instance field declared onclazz(not a subclass), for example a field on a superclass whenclazzis that superclass. -
get
public static <T> T get(Object o, String f, Class<T> type) throws NoSuchFieldException, IllegalAccessException Reads a field declared ono's runtime class. -
getPublic
public static <T> T getPublic(Object o, String f, Class<T> type) throws NoSuchFieldException, IllegalAccessException Reads a public field (including inherited) viaClass.getField(String). -
set
public static void set(Object o, String f, Object value) throws NoSuchFieldException, IllegalAccessException Writes a field declared ono's runtime class. -
open
- Throws:
IllegalStateException- ifAccessibleObject.trySetAccessible()returns false
-
getValueField
Reads a field value, callingAccessibleObject.trySetAccessible()whenAccessibleObject.canAccess(Object)is false (private, protected, package-private from another package, etc.).- Parameters:
obj- instance for an instance field, ornullfor a static fieldfield- field to read; not null- Throws:
IllegalAccessException
-
setValueField
public static void setValueField(Object obj, Field field, Object value) throws IllegalAccessException Writes a field value, callingAccessibleObject.trySetAccessible()whenAccessibleObject.canAccess(Object)is false.- Throws:
IllegalStateException- if the field isfinalIllegalAccessException
-
getAllDeclaredFields
Declared fields fromtypeand its superclasses, superclass first, excludingObject. Does not change accessibility or filter static/synthetic fields. -
findDeclaredField
Field namednameontypeor a superclass, made accessible, ornull. -
findDeclaredField
Field namednamewith exactfieldTypeontypeor a superclass, made accessible, ornull. -
getAllDeclaredMethods
Declared methods fromtypeand its superclasses, superclass first, excludingObject. Does not change accessibility or filter bridges/synthetics. -
findMethod
Method namednamewith the given parameter types ontype, a superclass, or an implemented interface (most specific class first). Made accessible, ornull. -
findMethod
Method namednamewithparamCountparameters ontype, a superclass, or an implemented interface (most specific class first). Parameter types are not compared, so a generic method is found after erasure. A non-bridge, non-synthetic method is preferred; a bridge or synthetic method is returned only when no other match exists. Made accessible, ornull. -
isEqualsMethod
trueifmethodisequals(Object). -
isHashCodeMethod
trueifmethodishashCode()with no parameters. -
isToStringMethod
trueifmethodistoString()with no parameters. -
isObjectMethod
-
declaresException
trueifmethoddeclaresexceptionTypeor a supertype of it. -
getMethodByName
Returns the first declared method whose name equalsnameMethod, ornullif none match. If several overloads share the name, which one is returned is unspecified. -
getMethodByAnnotation
Returns the first declared method annotated withclazz, ornull. -
getAllMethodsByAnnotation
public static List<Method> getAllMethodsByAnnotation(Class<?> entity, Class<? extends Annotation> clazz) Returns all declared methods that carry the given annotation (possibly empty). -
getClassOrPackageAnnotation
public static <A extends Annotation> A getClassOrPackageAnnotation(Class<?> clazz, Class<A> annotation) annotationonclazzitself, or else on itsPackage(typically frompackage-info). Superclasses and implemented interfaces are not searched.- Parameters:
clazz- class to inspectannotation- annotation type; must haveRetentionPolicy.RUNTIME- Returns:
- the annotation, or
nullwhen it is absent. A class in the unnamed package has no package annotation
-
hasClassOrPackageAnnotation
public static boolean hasClassOrPackageAnnotation(Class<?> clazz, Class<? extends Annotation> annotation) WhethergetClassOrPackageAnnotation(Class, Class)finds the annotation. -
getClassOrModuleAnnotation
public static <A extends Annotation> A getClassOrModuleAnnotation(Class<?> clazz, Class<A> annotation) annotationonclazzitself, or else on itsModule(typically frommodule-info). Superclasses and implemented interfaces are not searched.- Parameters:
clazz- class to inspectannotation- annotation type; must haveRetentionPolicy.RUNTIME- Returns:
- the annotation, or
nullwhen it is absent
-
hasClassOrModuleAnnotation
public static boolean hasClassOrModuleAnnotation(Class<?> clazz, Class<? extends Annotation> annotation) WhethergetClassOrModuleAnnotation(Class, Class)finds the annotation. -
unwrapProxy
User class behind a JDK, CGLIB, Byte Buddy, Hibernate, Mockito, or Javassist proxy. A JDK proxy with several application interfaces is returned unchanged.- Parameters:
type- class to unwrap; must not benull- Returns:
- the underlying class, or
typewhen it is not a recognized proxy
-
getConstructor
No-argument declared constructor, made accessible.- Throws:
NoSuchMethodException
-
getConstructor
public static <T> Constructor<T> getConstructor(Class<T> t, Class<?>... parameterTypes) throws NoSuchMethodException Declared constructor with the given parameter types, made accessible.- Throws:
NoSuchMethodException
-
resolveRecordConstructor
Resolves canonical constructor of a record class and makes it accessible.For record
MyRecord(int id, String name)returns constructor with parameter types(int.class, String.class).- Type Parameters:
T- record type- Parameters:
recordClass- record class token- Returns:
- canonical constructor for the record
- Throws:
IllegalArgumentException- ifrecordClassis not a recordIllegalStateException- if canonical constructor cannot be resolved
-
getInstance
public static <T> T getInstance(Class<T> t) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException getConstructor(type).newInstance()— no-arg instance. -
getInstance
public static <T> T getInstance(Class<T> t, Object... initargs) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException Resolves a constructor from the runtime classes ofinitargs(with primitive wrapper unboxing for matchingint,boolean, etc.). Fails if any argument isnullor if inferred types do not match an accessible constructor — then usegetInstance(Class, Class[], Object[]). -
getInstance
public static <T> T getInstance(Class<T> t, Class<?>[] parameterTypes, Object... initargs) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException Invokest.getDeclaredConstructor(parameterTypes).newInstance(initargs)with access opened. -
getAllInterfaces
Collects every interface type implemented (directly or indirectly) bycls: interfaces declared oncls, super-interfaces of those, and the same closure for each superclass up toObject. Each interface appears at most once; order is not specified.- Parameters:
cls- the class; must not benull- Returns:
- an immutable list of distinct interface
Classobjects - Throws:
NullPointerException- ifclsisnull
-
isInnerClass
Returns whetherclsis a nested type with a lexically enclosing class, i.e.Class.getEnclosingClass()is non-null (member classes, local classes, anonymous classes).- Parameters:
cls- the class to test, ornull- Returns:
falseifclsisnullor top-level; otherwise the result ofcls.getEnclosingClass() != null
-
getEnumMap
Builds a map from each enum constant's name to that constant.Equivalent to
getEnumMap(enumClass, Enum::name).- Parameters:
enumClass- the enum class; must not benulland must be an enum type- Returns:
- a new map (typically a
HashMap, perCollectors.toMap(java.util.function.Function<? super T, ? extends K>, java.util.function.Function<? super T, ? extends U>)) - Throws:
NullPointerException- ifenumClassorClass.getEnumConstants()isnull
-
getEnumMap
public static <E extends Enum<E>,K> Map<K,E> getEnumMap(Class<E> enumClass, Function<? super E, ? extends K> keyExtractor) Builds a map from a derived key (per constant) to the enum constant, for example a numerictypefield exposed by a getter.private static final Map<Integer, ValueType> BY_TYPE = getEnumMap(ValueType.class, ValueType::getType);Duplicate keys produce
IllegalStateExceptionfromCollectors.toMap(java.util.function.Function<? super T, ? extends K>, java.util.function.Function<? super T, ? extends U>).- Type Parameters:
E- enum typeK- key type (e.g.Integerfor anintcode)- Parameters:
enumClass- the enum class; must not benulland must be an enum typekeyExtractor- function producing the map key for each constant; must not benull- Returns:
- a new map from extracted key to constant (see
Collectors.toMap(java.util.function.Function<? super T, ? extends K>, java.util.function.Function<? super T, ? extends U>)) - Throws:
NullPointerException- ifenumClass,keyExtractor, or enum constants arenullIllegalStateException- if two constants map to the same key
-
castFieldValue
Casts a reflected field value totypewith primitive-aware behavior.Reflection APIs return boxed values for primitive fields; when
typeis a primitive token (for exampleint.class), this method first maps it to the wrapper type (for exampleInteger.class) before casting.- Parameters:
type- requested target type (primitive or reference)value- value to cast- Returns:
- cast value, or
nullifvalueisnull - Throws:
ClassCastException- ifvalueis not assignable to the effective cast type
-
propagate
Rethrowstas-is, including checked exceptions, without wrapping.nullbecomesNullPointerException.- Throws:
X extends Throwable
-
primitiveToWrapper
Maps a primitive type token to its wrapper type; non-primitive inputs are returned unchanged.- Parameters:
primitive- primitive class token (or any class)- Returns:
- wrapper class for primitives,
Void.classforvoid.class, otherwiseprimitive
-
getAllGenericParameterClasses
Extracts all generic argument classes from aType.Examples:
List<Integer>->[Integer.class]Map<Integer, String>->[Integer.class, String.class]
- Parameters:
genericType- generic type token, usually fromField.getGenericType()orMethod.getGenericReturnType()- Returns:
- list of classes found inside generic arguments; empty if none
-
getAllGenericParameterClasses
Shortcut overload forgetAllGenericParameterClasses(Type)using a reflected field.- Parameters:
field- reflected field; must not benull- Returns:
- list of classes found inside the field generic arguments; empty if none
-
getGenericInterfaceParameterClasses
public static List<Class<?>> getGenericInterfaceParameterClasses(Class<?> type, Class<?> rawInterface) Generic arguments of the firstrawInterfaceparameterization found ontypeor its superclasses. Empty if none. -
resolveTypeArgument
Resolves type argumentindexoftargetas implemented bytype, substituting interface type variables along the way.nullif not found.
-