saker.build Documentation TaskDoc JavaDoc Packages
public class ReflectUtils
Utility class containing functions related to reflection, types, and their manipulations.
Methods
public static int
Gets the hash code of the argument, assuming that it is a valid value for an annotation function.
public static String
Converts the argument objects to a string representation, assuming that it is a value value for an annotation function.
public static boolean
Checks if the arguments equal, assuming that they are valid values for an annotation function.
public static Object
Invokes clone on the argument array.
public static Object
createArray(Class<?> component, int length)
Creates an array with the given component type and length.
public static Object
createEmptyArray(Class<?> component)
Creates an empty array with the given component type.
public static Class<?>
findClassWithNameInHierarchy(Class<?> basetype, String classname)
Find the class instance with the given name in a hierarchy of classes.
public static Class<?>
Find the interface instance with the given name in a hierarchy of classes.
public static Class<?>
Find the type instance with the given name in a hierarchy of classes.
public static Set<String>
Gets the names of all inherited types of the argument type.
public static Set<Class<?>>
Gets all inherited types of the argument type.
public static Map<Class<?>, Integer>
Gets all inherited types of the argument type and maps them to their inheritance distance from the argument.
public static Set<Class<?>>
Gets all interfaces of the argument type.
public static <T extends Annotation> T
getAnnotation(Annotation[] annotations, Class<T> annottype)
Gets the annotation from the given array that has the same type as the specified type.
public static Class<?>
Gets a class instance that has the component type as the argument.
public static ByteArrayRegion
Tries to get the bytes for the given parameter class using its classloader.
public static String
Gets the name of the argument Class, if non-null.
public static <T> Constructor<T>
getConstructorAssert(Class<T> clazz, Class<?>... argtypes)
Gets the constructor with the specified parameter types from a class, throws an AssertionError if fails.
public static <T> Constructor<T>
getDeclaredConstructorAssert(Class<T> clazz, Class<?>... argtypes)
Gets the declared constructor with the specified parameter types from a class, throws an AssertionError if fails.
public static Field
getDeclaredFieldAssert(Class<?> clazz, String fieldname)
Gets the declared field with the specified name from a class, throws an AssertionError if fails.
public static Method
getDeclaredMethodAssert(Class<?> clazz, String methodname, Class<?>... argtypes)
Gets the declared method with the specified parameter types and name from a class, throws an AssertionError if fails.
public static MethodHandle
Gets a MethodHandle to the default method implementation of an interface method.
public static String
Gets the enclosing element canonical name of a given type.
public static Field
getFieldAssert(Class<?> clazz, String fieldname)
Gets the field with the specified name from a class, throws an AssertionError if fails.
public static Object
Gets the value of a field.
public static Set<Class<?>>
Gets the set of interfaces the argument class implements.
public static Method
getMethodAssert(Class<?> clazz, String methodname, Class<?>... argtypes)
Gets the method with the specified parameter types and name from a class, throws an AssertionError if fails.
public static Object
getModule(Class<?> type)
Gets the Module for the given type.
public static String
Gets the package name of the given type based on its name.
public static Object
Gets the default value for a primitive class.
public static ByteArrayRegion
getResourceBytes(ClassLoader classloader, String resourcename)
Gets the bytes of a resource from a ClassLoader given the name of the resource.
public static boolean
Checks if the given type has directly extends or implements the given type.
public static boolean
Checks if the subject classloader has a given parent classloader in its parent hierarchy.
public static <T> T
invokeConstructor(Constructor<T> constructor, Object... args)
Invokes the specified constructor with the given array of arguments.
public static Object
invokeDefaultMethodOn(Method method, Object object, Object... args)
Invokes the default implementation of an interface method.
public static Object
invokeMethod(Object obj, Method method, Object... args)
Invokes the specified method with the given array of arguments.
public static boolean
Checks if the argument object is an array.
public static boolean
Checks if the argument class is a boxed primitive.
public static boolean
Checks if the argument type represents either an enum class, or an anonymous enum inner class.
public static boolean
Checks if the argument classes represent the same classes in regards with primitive types.
public static Class<?>
lookupAccessClass(Lookup lookup, Class<?> targetClass)
Determines if a class can be accessed from the lookup context defined bythis Lookup object.
public static <T> T
newInstance(Class<T> clazz)
Creates a new instance of the argument class by invoking the no-arg constructor.
public static Class<?>
Looks up the primitive class instance for the specified name.
public static Class<?>
primitivize(Class<?> clazz)
Primitivises the argument class.
public static void
Reduces the argument type set to only contain types which do not have assignable duplicates.
public static void
Removes the elements from the argument iterable which are not interface types.
public static <T> Class<T>
Validation method for ensuring that the argument is an interface type.
public static void
setFieldValue(Field field, Object obj, Object value)
Sets the value of the field, handling null values for primitive types.
public static Class<?>
Unprimitivises the argument class.
public static Object
wrapIntoSingletonArray(Object value, Class<?> componenttype)
Wraps a single value into an array with a single element.
public static int annotationValueHashCode(Object value)
Gets the hash code of the argument, assuming that it is a valid value for an annotation function.

This function calls ArrayUtils.arrayHashCode(Object) for the argument if it is an array, else calls Object.hashCode() on it. This behaviour is in line with the requirements of Annotation.hashCode().

Although the null is not a valid annotation value, this function will return 0 for it.

valueThe value to get the hash code of.
The computed hash code.
Converts the argument objects to a string representation, assuming that it is a value value for an annotation function.

This function calls ArrayUtils.arrayToString(Object) if the argument is an array, else calls Object.toString() on it. This behaviour is in line with the typical implementation of Annotation.toString().

Although the null is not a valid annotation value, this function will return "null" for it.

valueThe value to get the string representation of.
The string representation.
public static boolean annotationValuesEqual(Object v1, Object v2)
Checks if the arguments equal, assuming that they are valid values for an annotation function.

This function calls ArrayUtils.arraysEqual(Object, Object) if the first argument is an array, else calls Object.equals(Object) on the first argument. This behaviour is in line with the requirements of Annotation.equals(Object).

Although the null is not a valid annotation value, this function will return false if only one of the arguments are null, and true if both of them are.

v1The first value.
v2The second value.
true if the arguments are considered to be equal.
public static Object cloneArray(Object array) throws IllegalArgumentException
Invokes clone on the argument array.

This method will always invoke .clone() on the array. If the array is a primitive array, it will be casted down and invoekd accordingly.

If the argument is null, null is returned.

This method creates a shallow clone, elements are not cloned.

arrayThe array to clone.
The cloned array.
IllegalArgumentExceptionIf the argument is not an array.
public static Object createArray(Class<?> component, int length) throws NullPointerException, NegativeArraySizeException
Creates an array with the given component type and length.

Same as:

 Array.newInstance(component, length);
 
componentThe component type.
lengthThe length of the created array.
An empty array with the given component type.
NullPointerExceptionIf the component type is null.
NegativeArraySizeExceptionIf the length is negative.
public static Object createEmptyArray(Class<?> component) throws NullPointerException
Creates an empty array with the given component type.

Same as:

 Array.newInstance(component, 0);
 
componentThe component type.
An empty array with the given component type.
NullPointerExceptionIf the component type is null.
public static Class<?> findClassWithNameInHierarchy(Class<?> basetype, String classname) throws NullPointerException
Find the class instance with the given name in a hierarchy of classes.

This method will try to find the class instance that has the same name as the argument. The method will look at the specified class argument, and check the super classes if they have the same name.

Note: Unlike findTypeWithNameInHierarchy(Class<?>, String) or findInterfaceWithNameInHierarchy(Class<?>, String), this method only searches for non-interfaces.

basetypeThe base type to start the search at.
classnameThe class name to search for.
The found class instance or null if not found.
NullPointerExceptionIf any of the arguments are null.
public static Class<?> findInterfaceWithNameInHierarchy(Class<?> basetype, String itfname) throws NullPointerException
Find the interface instance with the given name in a hierarchy of classes.

This method will try to find the interface instance that has the same name as the argument. The method will look at the specified class argument, and check the super classes and super interfaces if they have the same name.

Note: Unlike findTypeWithNameInHierarchy(Class<?>, String) or findClassWithNameInHierarchy(Class<?>, String), this method only searches for interfaces.

basetypeThe base type to start the search at.
itfnameThe interface name to search for.
The found interface instance or null if not found.
NullPointerExceptionIf any of the arguments are null.
public static Class<?> findTypeWithNameInHierarchy(Class<?> basetype, String typename) throws NullPointerException
Find the type instance with the given name in a hierarchy of classes.

This method will try to find the type instance that has the same name as the argument. The method will look at the specified class argument, and check the super classes and super interfaces if they have the same name.

Note: Unlike findInterfaceWithNameInHierarchy(Class<?>, String) or findClassWithNameInHierarchy(Class<?>, String), this method will find the interfaces and classes too.

basetypeThe base type to start the search at.
typenameThe type name to search for.
The found type instance or null if not found.
NullPointerExceptionIf any of the arguments are null.
public static Set<String> getAllInheritedTypeNames(Class<?> type)
Gets the names of all inherited types of the argument type.

This method will put the names of all superclasses and all interfaces into the result set, and return that. The result set will also contain the argument type name as well.

If the argument is null, null is returned.

The returned set has a deterministic iteration order, meaning that invoking this method between different invocations of the Java Virtual Machine will produce the same set with the same iteration order.

typeThe to get all inherited type names for.
A set of type names which are extended or implemented by the argument.
public static Set<Class<?>> getAllInheritedTypes(Class<?> type)
Gets all inherited types of the argument type.

This method will put all superclasses and all interfaces into the result set, and return that. The result set will also contain the argument type as well.

If the argument is null, null is returned.

The returned set has a deterministic iteration order, meaning that invoking this method between different invocations of the Java Virtual Machine will produce the same set with the same iteration order.

typeThe type to get all inherited types of.
A set of types which are extended or implemented by the argument.
Gets all inherited types of the argument type and maps them to their inheritance distance from the argument.

This method collects all classes and interfaces that the argument extends and implements. Each type is mapped to the inheritance distance of the type in relation to the argument.

The inheritance distance is defined as the number of 'hops' it takes to reach the inheritance declaration from the starting type.

E.g. for the type Integer:

 Integer : 0
 Number : 1 (via Integer)
 Comparable<Integer> : 1 (via Integer) 
 Serializable : 2 (via Number)
 Object : 2 (via Number)
 
The inheritance distances are minimized, meaning that if a type is present via multiple types (i.e. an interface is implemented by multiple supertypes), then the lesser of them will be taken.
typeThe type to get the inherited types of.
The inherited types mapped to their distance, or null if the argument is null.
public static Set<Class<?>> getAllInterfaces(Class<?> type)
Gets all interfaces of the argument type.

This method will collect all interfaces that the argument type extends. If the argument is already an interface, it will be part of the result set.

If the argument is null, null is returned.

The returned set has a deterministic iteration order, meaning that invoking this method between different invocations of the Java Virtual Machine will produce the same set with the same iteration order.

typeThe type to get the interfaces of.
A set of interfaces that the argument extends or null if the argument is null.
public static <T extends Annotation> T getAnnotation(Annotation[] annotations, Class<T> annottype)
Gets the annotation from the given array that has the same type as the specified type.

If any of the arguments are null, this method returns null.

annotationsThe annotations array to search in.
annottypeThe annotation type to look for.
The found annotation with the given type of null.
public static Class<?> getArrayClassWithComponent(Class<?> component) throws NullPointerException
Gets a class instance that has the component type as the argument.

This method is the same as:

 createEmptyArray(component).getClass();
 
The implementation of this method may be optimized on JDK12+, where the Class.arrayType() function is available.
componentThe component type.
The class with the given component type.
NullPointerExceptionIf the argument is null.
Tries to get the bytes for the given parameter class using its classloader.

This method gets the bytes for the corresponding class file from the defining classloader.

It is not ensured that the returned bytes are actually represent the given class parameter. This method should be used with care and for testing purposes only.

clazzThe class to get the bytes for.
The bytes of the corresponding class file resource or null if not found.
public static String getClassName(Class<?> type)
Gets the name of the argument Class, if non-null.
typeThe type to get the name of.
The name, or null if the argument is null.
public static <T> Constructor<T> getConstructorAssert(Class<T> clazz, Class<?>... argtypes) throws NullPointerException, AssertionError
Gets the constructor with the specified parameter types from a class, throws an AssertionError if fails.

This function will use Class.getConstructor(Class<?>...) to look up the appropriate constructor.

TThe type of the class.
clazzThe class to look up the constructor of.
argtypesThe argument types of the constructor.
The found constructor.
NullPointerExceptionIf the class argument is null.
AssertionErrorIf the constructor was not found, or not accessible due to security restrictions.
public static <T> Constructor<T> getDeclaredConstructorAssert(Class<T> clazz, Class<?>... argtypes) throws NullPointerException, AssertionError
Gets the declared constructor with the specified parameter types from a class, throws an AssertionError if fails.

This function will use Class.getDeclaredConstructor(Class<?>...) to look up the appropriate constructor.

TThe type of the class.
clazzThe class to look up the constructor of.
argtypesThe argument types of the constructor.
The found constructor.
NullPointerExceptionIf the class argument is null.
AssertionErrorIf the constructor was not found, or not accessible due to security restrictions.
public static Field getDeclaredFieldAssert(Class<?> clazz, String fieldname) throws NullPointerException, AssertionError
Gets the declared field with the specified name from a class, throws an AssertionError if fails.

This function will use Class.getDeclaredField(String) to look up the appropriate field.

clazzThe class to look up the field of.
fieldnameThe name of the field.
The found field.
NullPointerExceptionIf The class or field name arguments are null.
AssertionErrorIf the field was not found, or not accessible due to security restrictions.
public static Method getDeclaredMethodAssert(Class<?> clazz, String methodname, Class<?>... argtypes) throws NullPointerException, AssertionError
Gets the declared method with the specified parameter types and name from a class, throws an AssertionError if fails.

This function will use Class.getDeclaredMethod(String, Class<?>...) to look up the appropriate method.

clazzThe class to look up the method of.
methodnameThe name of the method.
argtypesThe argument types of the method.
The found method.
NullPointerExceptionIf The class or method name arguments are null.
AssertionErrorIf the method was not found, or not accessible due to security restrictions.
Gets a MethodHandle to the default method implementation of an interface method.

This method was tested to handle different Java runtime versions appropriately.

methodThe interface method to get the default method handle for.
The method handle.
NullPointerExceptionIf the argument is null.
ReflectiveOperationExceptionIf the operation fails.
Gets the enclosing element canonical name of a given type.

This method returns the canonical name of the enclosing Java element that declares the given type. For inner types, this returns the canonical name of the enclosing type. For top level type, this returns the name of the package it is declared in.

typeThe type.
The canonical name of the enclosing element.
public static Field getFieldAssert(Class<?> clazz, String fieldname) throws NullPointerException, AssertionError
Gets the field with the specified name from a class, throws an AssertionError if fails.

This function will use Class.getField(String) to look up the appropriate field.

clazzThe class to look up the field of.
fieldnameThe name of the field.
The found field.
NullPointerExceptionIf The class or field name arguments are null.
AssertionErrorIf the field was not found, or not accessible due to security restrictions.
public static Object getFieldValue(Field field, Object obj) throws IllegalAccessException
Gets the value of a field.

The field will be set to accessible by calling Field.setAccessible(boolean).

fieldThe field to get the value of.
objThe instance object for the field. May be null for static fields.
The value of the field.
public static Set<Class<?>> getInterfaces(Class<?> type) throws NullPointerException
Gets the set of interfaces the argument class implements.

This method will collect all the interfaces that a type implements. The returned set will be reduced, meaning that if an interface I is present, none of the interfaces that I extends will be in the resulting set. E.g. if a class implements List, it will not contain the interfaces for Collection, or Iterable.

If the argument is already an interface, the returned set will contain only the argument.

The returned set has a deterministic iteration order, meaning that invoking this method between different invocations of the Java Virtual Machine will produce the same set with the same iteration order.

typeThe class to get the implemented interfaces of.
A set of interfaces that the class implements.
NullPointerExceptionIf the argument is null.
public static Method getMethodAssert(Class<?> clazz, String methodname, Class<?>... argtypes) throws NullPointerException, AssertionError
Gets the method with the specified parameter types and name from a class, throws an AssertionError if fails.

This function will use Class.getMethod(String, Class<?>...) to look up the appropriate method.

clazzThe class to look up the method of.
methodnameThe name of the method.
argtypesThe argument types of the method.
The found method.
NullPointerExceptionIf The class or method name arguments are null.
AssertionErrorIf the method was not found, or not accessible due to security restrictions.
public static Object getModule(Class<?> type)
Gets the Module for the given type.

If the current code runs on Java 8 or below, this method returns null. Otherwise it returns Class.getModule().

Note: This method returns Object to keep compatibility with Java 8.

typeThe type to get the module of.
The module the type is member of or null if not applicable. null is also returned if the argument is null.
saker.util 0.8.2
public static String getPackageNameOf(Class<?> type)
Gets the package name of the given type based on its name.

The name of the type will be retrieved, and the part before the last '.' dot character will be returned. An empty string is returned if no dot character was found, representing the default package.

If the argument type is an inner class, the package name is returned nonetheless.

null is returned if the argument is null.

typeThe type.
The package name of the type derived from its name.
public static Object getPrimitiveClassDefaultValue(Class<?> primitiveclazz)
Gets the default value for a primitive class.

The argument may be a direct primitive class (such as int.class), or a boxed type (such as Integer).

primitiveclazzThe primitive class to get the default value for.
The default value, or null if not found. (In which case null would be the default value, as the argument is a reference type.)
public static ByteArrayRegion getResourceBytes(ClassLoader classloader, String resourcename) throws NullPointerException
Gets the bytes of a resource from a ClassLoader given the name of the resource.

This function will open the resource stream from the classloader usin ClassLoader.getResourceAsStream(String) and read the stream fully.

classloaderThe classloader to get the resource from.
resourcenameThe name of the resource.
The bytes of the resource or null if the resource was not found, or an I/O error occurred.
NullPointerExceptionIf any of the arguments are null.
public static boolean hasDirectSuperClassOrInterface(Class<?> type, Class<?> supertype) throws NullPointerException
Checks if the given type has directly extends or implements the given type.

This method will compare the given super type with the super class and interfaces of the examined type.

typeThe type to examine.
supertypeThe super type to search for.
true if either the super class or one of the implemented interfaces are the specified super type.
NullPointerExceptionIf any of the arguments are null.
public static boolean hasParentClassLoader(ClassLoader subject, ClassLoader parent)
Checks if the subject classloader has a given parent classloader in its parent hierarchy.

The subject classloader will be checked if it equals to the expected parent classloader. The same will be recursively checked for the parent classloader of the subject.

If the parent is null, this method will return true.

subjectThe subject classloader to check if it has the given parent.
parentThe parent to search for.
true if the parent classloader was found in the parent hierarchy of the subject.
Invokes the specified constructor with the given array of arguments.

The constructor will be set to accessible by calling Constructor.setAccessible(boolean).

constructorThe constructor to invoke.
argsThe arguments to pass to the constructor.
The created new instance.
public static Object invokeDefaultMethodOn(Method method, Object object, Object... args) throws NullPointerException, Throwable
Invokes the default implementation of an interface method.

This method was tested to handle different Java runtime versions appropriately.

methodThe default interface method to invoke.
objectThe interface object to invoke the method on.
argsThe arguments to the invocation.
The return value of the method invocation.
NullPointerExceptionIf the method is null.
ThrowableAny exception from the method call.
Invokes the specified method with the given array of arguments.

The method will be set to accessible by calling Method.setAccessible(boolean).

objThe instance object to call the method on. May be null for static methods.
methodThe method to invoke.
argsThe arguments to pass to the method.
The result of the method invocation.
public static boolean isArray(Object obj)
Checks if the argument object is an array.

It is determined by checking if its class is an array.

objThe object to check.
true if the argument is non-null and an array.
public static boolean isBoxedPrimitive(Class<?> clazz)
Checks if the argument class is a boxed primitive.

The class Void is considered to be a boxed primitive.

clazzThe class.
true if the argument is a boxed primitive.
public static boolean isEnumOrEnumAnonymous(Class<?> type)
Checks if the argument type represents either an enum class, or an anonymous enum inner class.

For enum objects which are inner classes as well, Class.isEnum() will return false. E.g.:

 public enum MyEnum {
 	FIRST_ENUM,
 	SECOND_ENUM {
 	};
 }
 // MyEnum.FIRST_ENUM.getClass() will return MyEnum.class
 // MyEnum.SECOND_ENUM.getClass() will return a type that is a subclass of MyEnum, but 
 
This method will check if the given type is either an enum, or an anonymous inner enum.

This method returns false if the argument is null.

typeThe type to check.
true if the argument type is an enum or anonymous inner enum class.
public static boolean isSamePrimitive(Class<?> c1, Class<?> c2)
Checks if the argument classes represent the same classes in regards with primitive types.

The function converts the argument classes to their primitive counterparts if any, and checks if they equal. The primitive counterpart is determined using primitivize(Class<?>).

If both arguments are null, true is returned.

c1The first class.
c2The second class.
true if the classes are the same in regards with the primitive types.
Determines if a class can be accessed from the lookup context defined bythis Lookup object.

The method calls Lookup.accessClass(targetClass) when run on Java 9+, while simply returns the targetClass when running on Java 8 or below.

lookupThe lookup object.
targetClassThe class to be access-checked.
The class that has been access-checked.
NullPointerExceptionIf any of the arguments are null.
IllegalAccessExceptionif the class is not accessible from the lookup class and previous lookup class, if present, using the allowed access modes.
SecurityExceptionif a security manager is present and it refuses access
saker.util 0.8.2
Creates a new instance of the argument class by invoking the no-arg constructor.

The no-arg constructor will be looked up, set to accessible, and invoked.

Same as:

 invokeConstructor(clazz.getDeclaredConstructor());
 
clazzThe class to create a new instance of.
The newly created instance.
Looks up the primitive class instance for the specified name.
nameThe name of the primitive class.
The primitive class, or null if not found.
NullPointerExceptionIf the argument is null.
public static Class<?> primitivize(Class<?> clazz)
Primitivises the argument class.

If the argument class is a boxed type of a primitive class, then the primitive class will be returned for it. In any other cases, the argument class will be returned.

Note that Void will be converted to void.class.

clazzThe class.
The primitivized class.
public static void reduceAssignableTypes(Set<Class<?>> classes)
Reduces the argument type set to only contain types which do not have assignable duplicates.

This method will remove any types in the argument collection for which there is a subclass or subinterface present.

E.g. If the type Collection and List is in it, then Collection will be removed, as it is already present in List, as that extends it.

Only the types will be removed which have at least one subclass of it present. E.g. If the argument contains Number, Float, and Double, only Number will be removed.

classesThe classes to reduce.
public static void removeNonInterfaces(Iterable<Class<?>> classes)
Removes the elements from the argument iterable which are not interface types.

If the argument is null, this method does nothing.

classesThe iterable of types.
public static <T> Class<T> requireInterface(Class<T> type) throws NullPointerException
Validation method for ensuring that the argument is an interface type.
typeThe type to validate.
The argument.
NullPointerExceptionIf the argument is null.
public static void setFieldValue(Field field, Object obj, Object value) throws IllegalAccessException, NullPointerException
Sets the value of the field, handling null values for primitive types.

The field will be set to accessible by calling Field.setAccessible(boolean).

If the field has a primitive type, and the value is null, the default value will be set for the field.

In any other cases, the Field.set(Object, Object) is called with the given arguments.

fieldThe field to set.
objThe instance object. May be null for static fields.
valueThe value to set.
public static Class<?> unprimitivize(Class<?> clazz)
Unprimitivises the argument class.

If the argument class is a primitive class, then the boxed type will be returned for it. In any other cases, the argument class will be returned.

Note that void.class will be converted to Void.

clazzThe class.
The unprimitivized class.
public static Object wrapIntoSingletonArray(Object value, Class<?> componenttype) throws NullPointerException
Wraps a single value into an array with a single element.
valueThe value to wrap.
componenttypeThe component type of the created array.
The array containing the single value.
NullPointerExceptionIf the component type is null.