Class KiwiReflection
- java.lang.Object
-
- org.kiwiproject.reflect.KiwiReflection
-
public class KiwiReflection extends Object
Some utilities related to reflection. Please read the WARNING below.Many of the methods are simply wrappers around JDK methods in
Class,Field, andMethod; they catch the various exceptions that can be thrown by the JDK methods and wrap them with a singleRuntimeReflectionException.WARNING: Note that some of the methods bypass the Java accessibility mechanism and/or change the visibility of a method or field. This makes Sonar very unhappy. See Sonar rule java:S3011 for more details, as well as rule SEC05-J from the SEI CERT Oracle Secure Coding Standard.
With the above warning in mind, there are good reasons to bypass Java's protections in some situations. And since this is a class specifically intended to be used in such situations, we intentionally suppress Sonar's warnings and assume you have good reasons to violate those rules.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classKiwiReflection.AccessorDefines the accessor method type.
-
Constructor Summary
Constructors Constructor Description KiwiReflection()
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static MethodfindAccessor(KiwiReflection.Accessor methodType, String fieldName, Class<?> targetClass, Class<?>... params)Finds a public accessor method of the givenmethodTypefor the specifiedfieldNamein the giventargetClass.static MethodfindAccessor(KiwiReflection.Accessor methodType, String fieldName, Object target, Class<?>... params)Finds an accessor method of the givenmethodTypefor the specifiedfieldNameintarget.static FieldfindField(Object target, String fieldName)Find a field by name in the specified target object, whether it is private or not.static MethodfindMethod(Class<?> targetClass, String methodName, Class<?>... params)Finds a public method having the given name and parameter types in the given class.static Optional<Method>findMethodOptionally(Class<?> targetClass, String methodName, Class<?>... params)Finds a public method having the given name and parameter types in the given class.static List<Method>findPublicAccessorMethods(Class<?> clazz)Finds all public accessor methods (getXxx/isXxxconforming to JavaBeans rules) in the given class (including superclasses).static List<Method>findPublicAccessorMethods(Object target)Finds all public accessor methods (getXxx/isXxxconforming to JavaBeans rules) in the class of the given object (including superclasses).static List<Method>findPublicMethods(Class<?> clazz, Predicate<Method> predicate)Finds all public methods in the given class (including superclasses) that satisfy the givenPredicate.static List<Method>findPublicMutatorMethods(Class<?> clazz)Finds all public mutator methods (setXxxconforming to JavaBeans rules) in the given class (including superclasses).static List<Method>findPublicMutatorMethods(Object target)Finds all public mutator methods (setXxxconforming to JavaBeans rules) in the class of the given object (including superclasses).static ObjectgetFieldValue(Object target, Field field)Get the value of a specific field in an object.static ObjectgetFieldValue(Object target, String fieldName)Get the value of a specific field in an object.static <T> TgetTypedFieldValue(Object target, Field field, Class<T> type)Get the value of a specific field in an object, cast to the specified type.static <T> TgetTypedFieldValue(Object target, String fieldName, Class<T> type)Get the value of a specific field in an object, cast to the specified type.static <T> TinvokeExpectingReturn(Method method, Object target, Class<T> returnType, Object... args)Invokes a method on an object expecting a return value of a specific type.static ObjectinvokeExpectingReturn(Method method, Object target, Object... args)Invokes a method on an object expecting a return value.static voidinvokeMutatorMethodsWithNull(Object target)Finds public mutator methods for the given object, then for reference types invokes the mutator supplyingnullas the argument.static voidinvokeMutatorMethodsWithNullIgnoringProperties(Object target, String... properties)Finds public mutator methods for the given object, then for reference types invokes the mutator supplyingnullas the argument except for property names contained inproperties.static voidinvokeMutatorMethodsWithNullIncludingOnlyProperties(Object target, String... properties)Finds public mutator methods for the given object, then for reference types invokes the mutator supplyingnullas the argument including only the property names contained inproperties.static voidinvokeMutatorMethodsWithNullSatisfying(Object target, Predicate<Method> methodPredicate)Finds public mutator methods for the given object, then for reference types invokes the mutator supplyingnullas the argument including only methods that satisfy the givenPredicate.static voidinvokeVoidReturn(Method method, Object target, Object... args)Invokes a method on an object expecting no return value.static booleanisPublicAccessorMethod(Method method)Checks whether the given method is a public accessor method (getXxx/isXxxconforming to JavaBeans rules).static booleanisPublicMutatorMethod(Method method)Checks whether the given method is a public mutator method (setXxxconforming to JavaBeans rules).static booleanisStrictlyGetAccessorMethod(Method method)Checks whether the given method is a public accessor method (onlygetXxxconforming to JavaBeans rules).static booleanisStrictlyIsAccessorMethod(Method method)Checks whether the given method is a public accessor method (onlyisXxxconforming to JavaBeans rules).static List<Field>nonStaticFieldsInHierarchy(Class<?> type)Builds a list of all the declared non-static fields in an object including all parent non-static fields.static voidsetFieldValue(Object target, Field field, Object value)Sets a value directly into the specified field in the target object.static voidsetFieldValue(Object target, String fieldName, Object value)Sets a value directly into the specified field in the target object.
-
-
-
Method Detail
-
findField
public static Field findField(Object target, String fieldName)
Find a field by name in the specified target object, whether it is private or not.Note specifically this method uses
Field.setAccessible(boolean)to make the returned field accessible and thus is subject to aSecurityExceptionorInaccessibleObjectException.- Parameters:
target- the target objectfieldName- the field name to find- Returns:
- the Field object
- Throws:
RuntimeReflectionException- if any error occurs finding the field- See Also:
Field.setAccessible(boolean)
-
getTypedFieldValue
public static <T> T getTypedFieldValue(Object target, String fieldName, Class<T> type)
Get the value of a specific field in an object, cast to the specified type.- Type Parameters:
T- the type parameter- Parameters:
target- the target objectfieldName- the field nametype- the type of object to return- Returns:
- the field value
- Throws:
RuntimeReflectionException- if any error occurs getting the field value (excluding type cast errors)ClassCastException- if the given return type is not correct
-
getFieldValue
public static Object getFieldValue(Object target, String fieldName)
Get the value of a specific field in an object.- Parameters:
target- the target objectfieldName- the field name- Returns:
- the field value
- Throws:
RuntimeReflectionException- if any error occurs finding the field or getting its value
-
getTypedFieldValue
public static <T> T getTypedFieldValue(Object target, Field field, Class<T> type)
Get the value of a specific field in an object, cast to the specified type.- Type Parameters:
T- the type parameter- Parameters:
target- the target objectfield- the field objecttype- the type of object to return- Returns:
- the field value
- Throws:
RuntimeReflectionException- if any error occurs getting the field value (excluding type cast errors)ClassCastException- if the given return type is not correct
-
getFieldValue
public static Object getFieldValue(Object target, Field field)
Get the value of a specific field in an object.- Parameters:
target- the target objectfield- the field object- Returns:
- the field value
- Throws:
RuntimeReflectionException- if any error occurs getting the field
-
setFieldValue
public static void setFieldValue(Object target, String fieldName, Object value)
Sets a value directly into the specified field in the target object.Subject to the restrictions of and exceptions thrown by
Field.set(Object, Object).- Parameters:
target- the target object in which the field residesfieldName- the field namevalue- the new value- Throws:
RuntimeReflectionException- if any error occurs setting the field value- See Also:
Field.set(Object, Object)
-
setFieldValue
public static void setFieldValue(Object target, Field field, Object value)
Sets a value directly into the specified field in the target object.Subject to the restrictions of and exceptions thrown by
Field.set(Object, Object).Think
- Parameters:
target- the target object in which the field residesfield- the field to setvalue- the new value- Throws:
RuntimeReflectionException- if any error occurs setting the field value- See Also:
Field.set(Object, Object)
-
nonStaticFieldsInHierarchy
public static List<Field> nonStaticFieldsInHierarchy(Class<?> type)
Builds a list of all the declared non-static fields in an object including all parent non-static fields.- Parameters:
type- the class to extract fields from- Returns:
- the list of fields in the given class plus fields from all ancestor (parent) classes
- See Also:
Class.getDeclaredFields()
-
findPublicAccessorMethods
public static List<Method> findPublicAccessorMethods(Object target)
Finds all public accessor methods (getXxx/isXxxconforming to JavaBeans rules) in the class of the given object (including superclasses).- Parameters:
target- the target object- Returns:
- list of public "getter" methods
- See Also:
Class.getMethods()
-
findPublicAccessorMethods
public static List<Method> findPublicAccessorMethods(Class<?> clazz)
Finds all public accessor methods (getXxx/isXxxconforming to JavaBeans rules) in the given class (including superclasses).- Parameters:
clazz- the target class- Returns:
- list of public "getter" methods
- See Also:
Class.getMethods()
-
isPublicAccessorMethod
public static boolean isPublicAccessorMethod(Method method)
Checks whether the given method is a public accessor method (getXxx/isXxxconforming to JavaBeans rules).- Parameters:
method- the method to check- Returns:
- true if method is a public accessor, false otherwise
-
isStrictlyGetAccessorMethod
public static boolean isStrictlyGetAccessorMethod(Method method)
Checks whether the given method is a public accessor method (onlygetXxxconforming to JavaBeans rules).Note this explicitly excludes the
Object.getClass()method.- Parameters:
method- the method to check- Returns:
- true if the method is a public "getXxx" method, false otherwise
-
isStrictlyIsAccessorMethod
public static boolean isStrictlyIsAccessorMethod(Method method)
Checks whether the given method is a public accessor method (onlyisXxxconforming to JavaBeans rules).- Parameters:
method- the method to check- Returns:
- true if the method is a public "isXxx" method, false otherwise
-
findPublicMutatorMethods
public static List<Method> findPublicMutatorMethods(Object target)
Finds all public mutator methods (setXxxconforming to JavaBeans rules) in the class of the given object (including superclasses).- Parameters:
target- the target object- Returns:
- list of public "setter" methods
- See Also:
Class.getMethods()
-
findPublicMutatorMethods
public static List<Method> findPublicMutatorMethods(Class<?> clazz)
Finds all public mutator methods (setXxxconforming to JavaBeans rules) in the given class (including superclasses).- Parameters:
clazz- the target class- Returns:
- list of public "setter" methods
- See Also:
Class.getMethods()
-
findPublicMethods
public static List<Method> findPublicMethods(Class<?> clazz, Predicate<Method> predicate)
Finds all public methods in the given class (including superclasses) that satisfy the givenPredicate.- Parameters:
clazz- the target classpredicate- the predicate to satisfy- Returns:
- a list of methods
- See Also:
Class.getMethods()
-
isPublicMutatorMethod
public static boolean isPublicMutatorMethod(Method method)
Checks whether the given method is a public mutator method (setXxxconforming to JavaBeans rules).- Parameters:
method- the method to check- Returns:
- true if the method is a public "setXxx" method, false otherwise
-
invokeMutatorMethodsWithNull
public static void invokeMutatorMethodsWithNull(Object target)
Finds public mutator methods for the given object, then for reference types invokes the mutator supplyingnullas the argument.The effect is thus to nullify the values of (mutable) properties in
targethaving a reference (non-primitive) type.- Parameters:
target- the object containing mutable properties exposed via public mutator methods- See Also:
findPublicMutatorMethods(Object)
-
invokeMutatorMethodsWithNullIgnoringProperties
public static void invokeMutatorMethodsWithNullIgnoringProperties(Object target, String... properties)
Finds public mutator methods for the given object, then for reference types invokes the mutator supplyingnullas the argument except for property names contained inproperties.The
propertiesvararg specifies the names of the properties to ignore. These names will be translated into the corresponding "setter" method name. For example, if "dateOfBirth" is the property name to ignore, then the "setDateOfBirth" method is the corresponding setter method and it will be ignored (not called).The effect is thus to nullify the values of (mutable) properties in
targethaving a reference (non-primitive) type, excluding the ones specified inproperties.- Parameters:
target- the object containing mutable properties exposed via public mutator methodsproperties- the property names to ignore, e.g. "firstName", "age", "zipCode"- See Also:
findPublicMutatorMethods(Object)
-
invokeMutatorMethodsWithNullIncludingOnlyProperties
public static void invokeMutatorMethodsWithNullIncludingOnlyProperties(Object target, String... properties)
Finds public mutator methods for the given object, then for reference types invokes the mutator supplyingnullas the argument including only the property names contained inproperties.The
propertiesvararg specifies the names of the properties to include. These names will be translated into the corresponding "setter" method name. For example, if "dateOfBirth" is the property name to include, then the "setDateOfBirth" method is the corresponding setter method and it will be called with a null argument.The effect is thus to nullify the values of (mutable) properties in
targethaving a reference (non-primitive) type, including only the ones specified inproperties.- Parameters:
target- the object containing mutable properties exposed via public mutator methodsproperties- the property names to include, e.g. "firstName", "age", "zipCode"- See Also:
findPublicMutatorMethods(Object)
-
invokeMutatorMethodsWithNullSatisfying
public static void invokeMutatorMethodsWithNullSatisfying(Object target, Predicate<Method> methodPredicate)
Finds public mutator methods for the given object, then for reference types invokes the mutator supplyingnullas the argument including only methods that satisfy the givenPredicate.When
methodPredicatereturnstrue, the mutator method is called with a null argument. When it returnsfalsethen the method is not called.The effect is thus to nullify the values of (mutable) properties in
targethaving a reference (non-primitive) type, including only the ones for whichmethodPredicatereturnstrue.- Parameters:
target- the object containing mutable properties exposed via public mutator methodsmethodPredicate- a Predicate that tests whether to include a mutator method
-
findMethodOptionally
public static Optional<Method> findMethodOptionally(Class<?> targetClass, String methodName, Class<?>... params)
Finds a public method having the given name and parameter types in the given class.- Parameters:
targetClass- the class in which to look for the methodmethodName- the name of the method to findparams- the parameter types of the method's argument list, if any- Returns:
- an
Optionalthat will contain theMethodif found. Otherwise returns an emptyOptionalin all other circumstances. - See Also:
Class.getMethod(String, Class[])
-
findAccessor
public static Method findAccessor(KiwiReflection.Accessor methodType, String fieldName, Object target, Class<?>... params)
Finds an accessor method of the givenmethodTypefor the specifiedfieldNameintarget.- Parameters:
methodType- the type of method to findfieldName- the field nametarget- the target objectparams- the method parameters- Returns:
- the found
Method - Throws:
RuntimeReflectionException- if any error occurs finding the accessor method
-
findAccessor
public static Method findAccessor(KiwiReflection.Accessor methodType, String fieldName, Class<?> targetClass, Class<?>... params)
Finds a public accessor method of the givenmethodTypefor the specifiedfieldNamein the giventargetClass. For example, given "firstName" as the field name andKiwiReflection.Accessor.SETas the method type, will attempt to find a publicsetFirstNameHandles primitive
booleanvs. referenceBooleandistinction transparently even ifKiwiReflection.Accessor.GETis passed as the method type for a primitive. In other words, this method will return theboolean isXxx()method if providedKiwiReflection.Accessor.GETbut the actual return type isprimitive.Allows for having a naming convention of instance variables starting with an underscore, e.g.
String _firstName, by stripping underscores from the field name. ThefieldNameargument can be supplied with or without a leading underscore. Note, however, that since this method removes all underscores from thefieldName, oddly named fields may produce exceptions.- Parameters:
methodType- the type of method to findfieldName- the field nametargetClass- the class in which the field residesparams- the method parameters (should be none for getters, and one for setters)- Returns:
- the found
Method - Throws:
RuntimeReflectionException- if any error occurs finding the accessor method
-
findMethod
public static Method findMethod(Class<?> targetClass, String methodName, Class<?>... params)
Finds a public method having the given name and parameter types in the given class.Use this when you expect the method to exist. If you are not sure, then use
findMethodOptionally(Class, String, Class[]).- Parameters:
targetClass- the class in which to look for the methodmethodName- the name of the method to findparams- the parameter types of the method's argument list, if any- Returns:
- the found
Methodobject - Throws:
RuntimeReflectionException- if any error occurs finding the method- See Also:
Class.getMethod(String, Class[])
-
invokeExpectingReturn
public static <T> T invokeExpectingReturn(Method method, Object target, Class<T> returnType, Object... args)
Invokes a method on an object expecting a return value of a specific type.- Type Parameters:
T- the return type parameter- Parameters:
method- the method to invoketarget- the object on which to invoke the methodreturnType- the expected return typeargs- optionally, the method arguments- Returns:
- result of calling the method (which could be
null), cast to typeT - Throws:
RuntimeReflectionException- if any error occurs invoking the method (excluding type cast errors)ClassCastException- if the given return type is not correct
-
invokeExpectingReturn
public static Object invokeExpectingReturn(Method method, Object target, Object... args)
Invokes a method on an object expecting a return value.- Parameters:
method- the method to invoketarget- the object on which to invoke the methodargs- optionally, the method arguments- Returns:
- result of calling the method (which could be
null) - Throws:
RuntimeReflectionException- if any error occurs invoking the method- See Also:
Method.invoke(Object, Object...)
-
invokeVoidReturn
public static void invokeVoidReturn(Method method, Object target, Object... args)
Invokes a method on an object expecting no return value.- Parameters:
method- the method to invoketarget- the object on which to invoke the methodargs- optionally, the method arguments- Throws:
RuntimeReflectionException- if any error occurs invoking the method- See Also:
Method.invoke(Object, Object...)
-
-