Class ReflectTools
- All Implemented Interfaces:
Serializable
For internal use only. May be renamed or removed in a future release.
- Since:
- 1.0
- See Also:
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic voidcheckClassAccessibility(Class<?> clazz) Makes a check whether theclazzis externally accessible for instantiation (e.g.static IllegalArgumentExceptionconvertInstantiationException(Exception exception, Class<?> clazz) Helper to handle all exceptions which might occur during class instantiation and returns anIllegalArgumentExceptionwith a descriptive error message hinting of what might be wrong with the class that could not be instantiated.static Class<?> convertPrimitiveType(Class<?> type) Converts the given primitive type to its boxed version.static <T> TcreateInstance(Class<T> cls) Creates an instance of the given class with a no-arg constructor.static TypecreateParameterizedType(Class<?> rawType, Type subType) Creates a parameterized type, e.g.static <T> TcreateProxyInstance(Class<T> proxyClass, Class<?> originalClass) Creates an instance of the givenproxyClasswith no-arg constructor.static Optional<ClassLoader> findClosestCommonClassLoaderAncestor(ClassLoader classLoaderA, ClassLoader classLoaderB) Finds the common ancestor of the twoClassLoaders.static Class<?> findCommonBaseType(Class<?> a, Class<?> b) Finds the most specific class that both provided classes extend from.static MethodfindMethod(Class<?> cls, String methodName, Class<?>... parameterTypes) Locates the method in the given class.static Optional<Annotation> getAnnotation(AnnotatedElement element, String annotationFqn) Gets annotation ofelementwhose FQN isannotationFqn.static ObjectgetAnnotationMethodValue(Annotation annotation, String methodName) Gets the annotation method return value.getConstantIntValues(Class<?> clazz) Collect all the integer values for public static final constants found for the given class.static MethodgetFunctionalMethod(Class<?> functionalClass) Get the functional interface method name defined for given interface class.static Class<?> getGenericInterfaceType(Class<?> clazz, Class<?> interfaceType) Finds the Class type for the generic interface class extended by given class if exists.getGenericInterfaceTypes(Class<?> clazz, Class<?> interfaceType) Finds the Class type for all parameters defined by the generic interface class extended by given class if exists.Finds a getter for a property in a bean type.getGetterMethods(Class<?> type) Return all the getter methods from the given type.static ObjectgetJavaFieldValue(Object object, Field field) Returns the value of the java field.static ObjectgetJavaFieldValue(Object object, Field field, Class<?> propertyType) Returns the value of the java field that is assignable to the property type.static SerializablegetPrimitiveDefaultValue(Class<?> primitiveType) Gets default value for givenprimitiveType.static StringgetPropertyName(Method method) Parses the property name from the given getter or setter method.static TypegetPropertyType(Method method) Returns property type from the given getter or setter method.getSetterMethods(Class<?> type) Return all the setter methods from the given type.static booleanhasAnnotation(AnnotatedElement element, String annotationFqn) Checks whether theelementhas annotation whose FQN isannotationFqn.static booleanhasAnnotationWithSimpleName(AnnotatedElement element, String simpleName) Checks whether theelementhas annotation whose simple name issimpleName.static booleanisCheckedException(Class<?> exceptionClass) Checks if the given exception class represents a checked exception.static booleanChecks whether the given method is a valid getter according to JavaBeans Specification.static booleanisGetterName(String methodName, boolean isBoolean) Checks whether the given method name is a valid getter name according to the JavaBeans Specification.static booleanisInstantiableService(Class<?> clazz) Check if a class can be instantiated via its default constructor via reflection.static booleanisNotObjectMethod(Method method) Returns whether the given method is NOT declared inObject.static booleanChecks whether the given method is a valid setter according to the JavaBeans Specification.static booleanisSetterName(String methodName) Checks whether the given method name is a valid setter name according to the JavaBeans Specification.static voidsetJavaFieldValue(Object object, Field field, Object value) Sets the value of a java field.
-
Constructor Details
-
ReflectTools
public ReflectTools()
-
-
Method Details
-
findMethod
public static Method findMethod(Class<?> cls, String methodName, Class<?>... parameterTypes) throws ExceptionInInitializerError Locates the method in the given class. Returns null if the method is not found. Throws an ExceptionInInitializerError if there is a problem locating the method as this is mainly called from static blocks.- Parameters:
cls- Class that contains the methodmethodName- The name of the methodparameterTypes- The parameter types for the method.- Returns:
- A reference to the method
- Throws:
ExceptionInInitializerError- Wraps any exception in anExceptionInInitializerErrorso this method can be called from a static initializer.
-
getJavaFieldValue
public static Object getJavaFieldValue(Object object, Field field) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException Returns the value of the java field.Uses getter if present, otherwise tries to access even private fields directly.
- Parameters:
object- The object containing the fieldfield- The field we want to get the value for- Returns:
- The value of the field in the object
- Throws:
InvocationTargetException- If the value could not be retrievedIllegalAccessException- If the value could not be retrievedIllegalArgumentException- If the value could not be retrieved
-
getJavaFieldValue
public static Object getJavaFieldValue(Object object, Field field, Class<?> propertyType) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException Returns the value of the java field that is assignable to the property type.Uses getter if a getter for the correct return type is present, otherwise tries to access even private fields directly. If the java field is not assignable to the property type throws an IllegalArgumentException.
- Parameters:
object- The object containing the fieldfield- The field we want to get the value forpropertyType- The type the field must be assignable to- Returns:
- The value of the field in the object
- Throws:
InvocationTargetException- If the value could not be retrievedIllegalAccessException- If the value could not be retrievedIllegalArgumentException- If the value could not be retrieved
-
setJavaFieldValue
public static void setJavaFieldValue(Object object, Field field, Object value) throws IllegalArgumentException Sets the value of a java field.- Parameters:
object- The object containing the fieldfield- The field we want to set the value forvalue- The value to set- Throws:
IllegalArgumentException- If the value could not be assigned to the field
-
convertPrimitiveType
Converts the given primitive type to its boxed version.- Parameters:
type- the primitive type to convert- Returns:
- the corresponding boxed type
-
getPrimitiveDefaultValue
Gets default value for givenprimitiveType.- Parameters:
primitiveType- the primitive type- Returns:
- the corresponding default value
-
isSetter
Checks whether the given method is a valid setter according to the JavaBeans Specification.- Parameters:
method- the method to check- Returns:
trueif the method is a setter,falseif not
-
isSetterName
Checks whether the given method name is a valid setter name according to the JavaBeans Specification.- Parameters:
methodName- the method name to check- Returns:
trueif the method name is a setter name,falseif not
-
isGetterName
Checks whether the given method name is a valid getter name according to the JavaBeans Specification.- Parameters:
methodName- the method name to checkisBoolean- whether the method is getter for boolean type- Returns:
trueif the method name is a getter name,falseif not
-
isGetter
Checks whether the given method is a valid getter according to JavaBeans Specification.- Parameters:
method- the method to check- Returns:
trueif the method is a getter,falseif not
-
getGetterMethods
Return all the getter methods from the given type.Any getter methods from
Objectare excluded.- Parameters:
type- the type to get getters from- Returns:
- a stream of getter methods
-
getSetterMethods
Return all the setter methods from the given type.- Parameters:
type- the type to get setters from- Returns:
- a stream of setter methods
-
isNotObjectMethod
Returns whether the given method is NOT declared inObject.- Parameters:
method- the method to check- Returns:
trueif method is NOT declared in Object,falseif it is
-
getPropertyName
Parses the property name from the given getter or setter method.If the given method does not have a valid setter or getter name, this method may produce unexpected results.
- Parameters:
method- the method to parse- Returns:
- the name of the property
- See Also:
-
getPropertyType
Returns property type from the given getter or setter method.- Parameters:
method- the method to inspect- Returns:
- the property type
- See Also:
-
createInstance
Creates an instance of the given class with a no-arg constructor.Catches all exceptions which might occur and wraps them in a
IllegalArgumentExceptionwith a descriptive error message hinting of what might be wrong with the class that could not be instantiated.- Type Parameters:
T- the instance type- Parameters:
cls- the class to instantiate- Returns:
- an instance of the class
-
createProxyInstance
Creates an instance of the givenproxyClasswith no-arg constructor.Catches all exceptions which might occur and wraps them in a
IllegalArgumentExceptionwith a descriptive error message hinting of what might be wrong with the class that could not be instantiated. Descriptive message is derived based on the information about theoriginalClass.- Type Parameters:
T- type of a proxy class- Parameters:
proxyClass- the proxy class to instantiateoriginalClass- the class that is used to determine exception description, if creation fails- Returns:
- instance of a proxyClass
- Throws:
IllegalArgumentException- if class instance creation fails
-
convertInstantiationException
public static IllegalArgumentException convertInstantiationException(Exception exception, Class<?> clazz) Helper to handle all exceptions which might occur during class instantiation and returns anIllegalArgumentExceptionwith a descriptive error message hinting of what might be wrong with the class that could not be instantiated. Descriptive message is derived based on the information about theclazz.- Parameters:
exception- original exceptionclazz- instantiation target class- Returns:
- an IllegalArgumentException with descriptive message
-
checkClassAccessibility
Makes a check whether theclazzis externally accessible for instantiation (e.g. it's not inner class (nested and not static) and is not a local class).- Parameters:
clazz- type to check
-
createParameterizedType
Creates a parameterized type, e.g.List<Bean>.- Parameters:
rawType- the raw type, e.g.ListsubType- the sub type, e.g.Bean- Returns:
- a parameterized type
-
getGenericInterfaceType
Finds the Class type for the generic interface class extended by given class if exists.- Parameters:
clazz- class that should extend interfaceinterfaceType- class type of interface to get generic for- Returns:
- Class if found else
null
-
getGenericInterfaceTypes
Finds the Class type for all parameters defined by the generic interface class extended by given class if exists.- Parameters:
clazz- class that should extend interfaceinterfaceType- class type of interface to get generic for- Returns:
- List of Class if found else empty List, never null
-
getGetter
Finds a getter for a property in a bean type.- Parameters:
beanClass- the bean type, notnullpropertyName- the property name, notnull- Returns:
- a getter method, or an empty optional if the bean type has no readable property with the provided name
-
isCheckedException
Checks if the given exception class represents a checked exception.- Parameters:
exceptionClass- the class to check- Returns:
trueif the class represents a checked exception, false otherwise
-
getFunctionalMethod
Get the functional interface method name defined for given interface class.- Parameters:
functionalClass- interface class to get the functional method for- Returns:
- functional interface method
-
getConstantIntValues
Collect all the integer values for public static final constants found for the given class.- Parameters:
clazz- class to collect constants from- Returns:
- list of all integer constants in class
-
findCommonBaseType
Finds the most specific class that both provided classes extend from.- Parameters:
a- one class to get the base type for, notnullb- another class to get the base type for, notnull- Returns:
- the most specific base class, not
null - Throws:
IllegalArgumentException- if a or b are interfaces or primitive types
-
findClosestCommonClassLoaderAncestor
public static Optional<ClassLoader> findClosestCommonClassLoaderAncestor(ClassLoader classLoaderA, ClassLoader classLoaderB) Finds the common ancestor of the twoClassLoaders. The class loaders themselves are acceptable ancestors; If they are equal,classLoaderAis returned. An empty optional is returned if the two class loaders aren't equal, no shared ancestor is found, or the implementation of the class loader treats bootstrap class loader asnullwhen it is the parent of a class loaders (seeClassLoader.getParent().- Parameters:
classLoaderA- class loader AclassLoaderB- class loader B- Returns:
- a common ancestor both class loaders share, or an empty optional
if there is no shared ancestor. Or if the implementation treats
bootstrap loaders as
null(as perClassLoader.getParent()).
-
hasAnnotation
Checks whether theelementhas annotation whose FQN isannotationFqn.- Parameters:
element- annotated element (field, method, etc.)annotationFqn- annotation FQN- Returns:
trueiselementhas annotation whose FQN isannotationFqn,falseotherwise
-
hasAnnotationWithSimpleName
Checks whether theelementhas annotation whose simple name issimpleName.- Parameters:
element- annotated element (field, method, etc.)simpleName- annotation simple name- Returns:
trueiselementhas annotation whose simple name issimpleName,falseotherwise
-
getAnnotationMethodValue
Gets the annotation method return value.- Parameters:
annotation- the annotationmethodName- the method name- Returns:
- an optional value, or an empty optional if element has no
annotation with required
annotationFqn
-
getAnnotation
Gets annotation ofelementwhose FQN isannotationFqn.- Parameters:
element- annotated element (field, method, etc.)annotationFqn- annotation FQN- Returns:
- an optional annotation, or an empty optional if element has no
annotation with required
annotationFqn
-
isInstantiableService
Check if a class can be instantiated via its default constructor via reflection.- Parameters:
clazz- the class to check- Returns:
- true if the class can be instantiated, otherwise false
-