Modifier and Type | Field and Description |
---|---|
private static Map<Class<?>,Class<?>> |
COLLECTIONS
Default implementations for collection interfaces.
|
private static Map<Class<?>,Class<?>> |
LISTS
Default implementations for list interfaces.
|
private static Log |
log
Class logger.
|
private static Map<Class<?>,Class<?>> |
MAPS
Default implementations for maps interfaces.
|
Modifier | Constructor and Description |
---|---|
protected |
Classes()
Prevent default constructor synthesis but allow sub-classing.
|
Modifier and Type | Method and Description |
---|---|
static Method |
findMethod(Class<?> clazz,
String methodName)
Find method with given name and unknown parameter types.
|
static <T> Class<T> |
forName(String className)
Load named class using current thread context class loader.
|
static <T> Class<T> |
forNameEx(String className)
Get class by name with checked exception.
|
static <T> Class<T> |
forOptionalName(String className)
Get optional class by name or null if class not found.
|
static Class<?> |
forType(Type type)
Get the underlying class for a type, or null if the type is a variable type.
|
static String |
getCallerMethod()
Get source line for the caller method.
|
static Field |
getField(Class<?> clazz,
String fieldName)
Get class field with unchecked runtime exception.
|
static Field |
getFieldEx(Class<?> clazz,
String fieldName)
Get class or superclass named field with checked exception.
|
static <T> T |
getFieldValue(Object object,
Class<?> clazz,
String fieldName)
Get instance field value declared into superclass.
|
private static <T> T |
getFieldValue(Object object,
Class<?> clazz,
String fieldName,
Class<T> fieldType,
boolean optional)
Helper method for field value retrieval.
|
static <T> T |
getFieldValue(Object object,
Field field)
Get object instance field value.
|
static <T> T |
getFieldValue(Object object,
String fieldName)
Get instance or class field value.
|
static Class<?> |
getImplementation(Map<Class<?>,Class<?>> implementationsRegistry,
Type interfaceType)
Lookup implementation into given registry, throwing exception if not found.
|
static <T extends List<?>> |
getListDefaultImplementation(Type listType)
Get default implementation for requested list type.
|
static Method |
getMethod(Class<?> clazz,
String methodName,
Class<?>... parameterTypes)
Get class method with runtime exception.
|
static Field |
getOptionalField(Class<?> clazz,
String fieldName)
Get class field or null if not found.
|
static <T> T |
getOptionalFieldValue(Object object,
String fieldName,
Class<T>... fieldType)
Get optional field value from instance or class.
|
static String |
getPackageResource(Class<?> type,
String resourceName)
Get resource name qualified with the package of a given class.
|
static Class<?>[] |
getParameterTypes(Object... arguments)
Get method formal parameter types inferred from actual invocation arguments.
|
static URL |
getResource(String name)
Retrieve URL of the named resource or null if not found.
|
private static URL |
getResource(String name,
ClassLoader[] classLoaders)
Get named resource URL from a list of class loaders.
|
static byte[] |
getResourceAsBytes(String name)
Retrieve binary resource as array of bytes.
|
static File |
getResourceAsFile(String name)
Get file resource, that is, resource with file protocol.
|
static Reader |
getResourceAsReader(String name)
Convenient method to retrieve named resource as reader.
|
static InputStream |
getResourceAsStream(String name)
Retrieve resource, identified by qualified name, as input stream.
|
private static InputStream |
getResourceAsStream(String name,
ClassLoader[] classLoaders)
Get named resource input stream from a list of class loaders.
|
static String |
getResourceAsString(String name)
Retrieve text resource content as a string.
|
static boolean |
hasMethod(Class<?> clazz,
String methodName,
Class<?>... parameterTypes)
Predicate to test if a class do possess a given method.
|
static <T> T |
invoke(Object object,
Class<?> clazz,
String methodName,
Object... arguments)
Reflexively executes a method on an object.
|
private static Object |
invoke(Object object,
Method method,
Object... arguments)
Do the actual reflexive method invocation.
|
static <T> T |
invoke(Object object,
String methodName,
Object... arguments)
Invoke instance or class method with arguments.
|
static void |
invokeOptionalSetter(Object object,
String name,
String value)
Variant for
invokeSetter(Object, String, String) but no exception if setter not found. |
static void |
invokeSetter(Object object,
String name,
String value)
Invoke setter method on given object instance.
|
static boolean |
isInstantiable(Class<?> clazz)
Test if class is not an interface or abstract and have default constructor.
|
static Collection<String> |
listPackageResources(String packageName,
String fileNamesPattern)
List package resources from local classes or from archives.
|
private static Collection<String> |
listPackageResources(URL packageURL,
String packagePath,
String fileNamesPattern)
Get package resources that match file name pattern.
|
static <S> S |
loadOptionalService(Class<S> serviceInterface)
Load service of requested interface returning null if service provider not found.
|
static <S> S |
loadService(Class<S> serviceInterface)
Load service of requested interface throwing exception if provider not found.
|
static <S> S |
loadService(Class<S> serviceInterface,
ClassLoader classLoader)
Load service of requested interface using given class loader.
|
private static NoSuchBeingException |
missingConstructorException(Class<?> clazz,
Object... arguments)
Helper for missing constructor exception.
|
static <T extends Collection<?>> |
newCollection(Type type)
Create new collection of given type.
|
static <T> T |
newInstance(Class<T> clazz,
Object... arguments)
Create a new object instance of specified class.
|
static <T> T |
newInstance(String className,
Object... arguments)
Create a new instance.
|
static <T> T |
newInstance(Type type,
Object... arguments)
Create instance of requested type - objects, collections or maps, using a constructor with given arguments.
|
static <T extends List<?>> |
newList(Type type)
Create new list of given raw type.
|
static <T extends Map<?,?>> |
newMap(Type type)
Create new map of given type.
|
private static <T> T |
newRegisteredInstance(Map<Class<?>,Class<?>> implementationsRegistry,
Type interfaceType)
Lookup implementation for requested interface into given registry and return a new instance of it.
|
static void |
setFieldValue(Object object,
Class<?> clazz,
String fieldName,
Object value)
Set instance field declared into superclass.
|
static void |
setFieldValue(Object object,
Field field,
Object value)
Set field value for object instance, or class if given object instance is null.
|
static void |
setFieldValue(Object object,
String fieldName,
Object value)
Set instance or class field value.
|
static void |
setFieldValues(Object object,
String fieldName,
String valuesString)
Set values to a field of array or collection type.
|
static <T> T |
unproxy(T instance)
Return wrapped instance of a Java Proxy implemented on a
InstanceInvocationHandler handler. |
private static Log log
private static Map<Class<?>,Class<?>> COLLECTIONS
protected Classes()
public static <T> Class<T> forName(String className) throws NoSuchBeingException, ClassCastException, NullPointerException
This logic is designed for Tomcat class loading algorithm. Libraries are loaded using a separated class loader and every application has its own class loader. This method algorithm allows for a class used by an application to be found either by current thread or by library class loader.
Considering above, note that there is a subtle difference compared with standard Class.forName(String)
counterpart: this method uses current thread context loader
whereas Java standard uses
current loader
. Maybe not obvious, this 'semantic' difference could lead to class not found on Java
standard while this utility method find the class. For example, a class defined by an web application could not be
found by Java Class.forName
method running inside a class defined by library.
T
- class to auto-cast named class.className
- qualified class name, not null.NoSuchBeingException
- if class not found.ClassCastException
- if found class cannot cast to requested auto-cast type.NullPointerException
- if className
argument is null.public static <T> Class<T> forOptionalName(String className)
Uses current thread context class loader to locate and load requested class. If current thread context class loader is null or fails to find requested class try with this utility class class loader.
This logic is designed for Tomcat class loading algorithm. Libraries are loaded using a separated class loader and every application has its own class loader. This method algorithm allows for a class used by an application to be found either by current thread or by library class loader.
Considering above, note that there is a subtle difference compared with standard Class.forName(String)
counterpart: this method uses current thread context loader
whereas Java standard uses
current loader
. Maybe not obvious, this 'semantic' difference could lead to class not found on Java
standard while this utility method find the class. For example, a class defined by an web application could not be
found by Java Class.forName
method running inside a class defined by library.
T
- class to auto-cast named class.className
- requested class name, null tolerated.ClassCastException
- if found class cannot cast to requested auto-cast type.public static <T> Class<T> forNameEx(String className) throws ClassNotFoundException, ClassCastException, NullPointerException
forName(String)
but throws checked exception in the
event requested class is not found.T
- class to auto-cast named class.className
- requested class name, not null.ClassNotFoundException
- if class not found.ClassCastException
- if found class cannot cast to requested auto-cast type.NullPointerException
- if className
argument is null.public static <S> S loadService(Class<S> serviceInterface)
loadService(Class)
usable when a missing service implementation is a run-time stopper.S
- service typeserviceInterface
- service interface.NoProviderException
- if service provider not found on run-time.public static <S> S loadService(Class<S> serviceInterface, ClassLoader classLoader)
S
- service type.serviceInterface
- service interface,classLoader
- class loader.NoProviderException
- if service provider not found on run-time.public static <S> S loadOptionalService(Class<S> serviceInterface)
S
- service type.serviceInterface
- service interface.public static boolean isInstantiable(Class<?> clazz)
Class.newInstance()
has no reason to fail.clazz
- class to test if instantiable.public static Class<?>[] getParameterTypes(Object... arguments)
arguments
- variable number of method arguments.public static <T> T invoke(Object object, String methodName, Object... arguments) throws Exception
object
argument is a Class
delegate invoke(Object, Class, String, Object...)
with first argument set to null; otherwise
object
is passed as first argument and its class the second.T
- returned value type.object
- object instance or class,methodName
- method name,arguments
- variable number of arguments.NoSuchBeingException
- if method is not found.Exception
- if invocation fail for whatever reason including method internals.public static <T> T invoke(Object object, Class<?> clazz, String methodName, Object... arguments) throws Exception
Implementation note: this method is a convenient way to invoke a method when one knows actual parameters but not
strictly formal parameters types. When formal parameters include interfaces or abstract classes or an actual
parameter is null there is no way to infer formal parameter type from actual parameter instance. The only option
left is to locate method by name and if overloads found uses best effort to determine the right parameter list. For
this reason, on limit is possible to invoke the wrong method. Anyway, this method is designed for tests
logic and best effort is good enough. The same is true for invoke(Object, String, Object...)
.
T
- returned value type.object
- object instance,clazz
- object class one of its superclass,methodName
- method name,arguments
- variable number of arguments.NoSuchBeingException
- if method is not found.Exception
- if invocation fail for whatever reason including method internals.public static void invokeSetter(Object object, String name, String value) throws NoSuchMethodException, Exception
Strings.getMethodAccessor(String, String)
and value string is converted to method parameter type using
Converter
facility. For this reason set parameter type should have a converter registered.
This method has no means to determine method using Class.getMethod(String, Class...)
because parameter
value is always string and setter parameter type is unknown. For this reason this method uses
findMethod(Class, String)
. Note that find method searches for named method on object super hierarchy too.
object
- object instance,name
- setter name, method name only without set
prefix, dashed case accepted,value
- value to set, string value that is converted to setter method parameter type.NoSuchMethodException
- if setter not found.Exception
- if invocation fail for whatever reason including method logic.public static void invokeOptionalSetter(Object object, String name, String value) throws Exception
invokeSetter(Object, String, String)
but no exception if setter not found.object
- object instance,name
- setter name,value
- value to set.Exception
- if invocation fail for whatever reason including method logic.private static Object invoke(Object object, Method method, Object... arguments) throws Exception
object
- object instance,method
- reflexive method,arguments
- variable number of arguments.Exception
- if invocation fail for whatever reason including method internals.public static boolean hasMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes)
NoSuchMethodException
if method not found. This method does not throws exception but returns a boolean.clazz
- reflexive class,methodName
- method name,parameterTypes
- formal parameters list.public static Method getMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes)
NoSuchMethodException
if method is missing,
behavior that is not desirable for this library. This method uses runtime, unchecked NoSuchBeingException
instead. Returned method has accessibility set to true.clazz
- Java class to return method from,methodName
- method name,parameterTypes
- method formal parameters.NoSuchBeingException
- if does not found the method.public static Method findMethod(Class<?> clazz, String methodName) throws NoSuchMethodException
NoSuchMethodException
. If there are overloaded
methods returns one of them but there is no guarantee which one. Returned method has accessibility enabled.
Implementation note: this method is inherently costly since at worst case needs to traverse all class methods. It is recommended to be used with external method cache.
clazz
- Java class to return method from,methodName
- method name.NoSuchMethodException
- if there is no method with requested name.public static String getCallerMethod()
public static Field getField(Class<?> clazz, String fieldName)
NoSuchFieldException
if field is
missing, behavior that is not desirable for this library. This method uses runtime, unchecked
NoSuchBeingException
instead. Returned field has accessibility set to true.clazz
- Java class to return field from,fieldName
- field name.NoSuchBeingException
- if field not found.public static Field getOptionalField(Class<?> clazz, String fieldName)
clazz
- Java class to return field from,fieldName
- field name.public static Field getFieldEx(Class<?> clazz, String fieldName) throws NoSuchFieldException
NoSuchFieldException
.clazz
- class to search for named field,fieldName
- the name of field to retrieve.NoSuchFieldException
- if class or superclass has no field with requested name.public static <T> T getFieldValue(Object object, Field field)
getField(Class, String)
.T
- field type.object
- instance to retrieve field value from,field
- object reflective field.public static <T> T getFieldValue(Object object, String fieldName)
object
argument
is a Class
retrieve class static field.T
- field value type.object
- instance or class to retrieve field value from,fieldName
- field name.NullPointerException
- if object argument is null.NoSuchBeingException
- if field is missing.BugError
- if object
is a class and field is not static or if object
is an instance
and field is static.@SafeVarargs public static <T> T getOptionalFieldValue(Object object, String fieldName, Class<T>... fieldType)
T
- field value type.object
- instance or class to retrieve field value from,fieldName
- field name,fieldType
- optional desired field type.public static <T> T getFieldValue(Object object, Class<?> clazz, String fieldName)
T
- field value type.object
- instance to retrieve field value from,clazz
- instance superclass,fieldName
- field name.NoSuchBeingException
- if field is missing.private static <T> T getFieldValue(Object object, Class<?> clazz, String fieldName, Class<T> fieldType, boolean optional)
optional
argument: if true returns null,
otherwise throws exception.T
- field value type.object
- instance to retrieve field value from or null if static field,clazz
- class or superclass where field is actually declared,fieldName
- field name,fieldType
- desired field type or null,optional
- if true, return null if field is missing.NoSuchBeingException
- if optional flag is false and field is missing.BugError
- if object is null and field is not static or if object is not null and field is static.public static void setFieldValue(Object object, Field field, Object value) throws IllegalArgumentException, BugError
value
to field type: if value
is
a string and field type is not, delegates Converter.asObject(String, Class)
. Anyway, if value
is not a string it should be assignable to field type otherwise bug error is thrown.object
- instance to set field value to or null,field
- reflective field,value
- field value, possible null.IllegalArgumentException
- if field
parameter is null.ConverterException
- if attempt to convert string value to field type but there is no registered converted
for that type.BugError
- if value is not assignable to field type.public static void setFieldValue(Object object, String fieldName, Object value)
object
argument is a class, named field should be static; otherwise exception is thrown.
This setter tries to adapt value
to field type: if value
is a string and field type is
not, delegates Converter.asObject(String, Class)
. Anyway, if value
is not a string it should
be assignable to field type otherwise bug error is thrown.
object
- instance or class to set field value to,fieldName
- field name,value
- field value.IllegalArgumentException
- if object
or fieldName
argument is null.NoSuchBeingException
- if field not found.BugError
- if object is null and field is not static or if object is not null and field is static.BugError
- if value is not assignable to field type.public static void setFieldValue(Object object, Class<?> clazz, String fieldName, Object value)
object
- instance to set field value to or null if field is static,clazz
- instance superclass where field is declared,fieldName
- field name,value
- field value.NoSuchBeingException
- if field not found.BugError
- if object is null and field is not static or if object is not null and field is static.public static void setFieldValues(Object object, String fieldName, String valuesString)
valuesString
parameter that is a list of comma separated value objects. Split values
string and converter every resulting item to field component type.object
- instance to set field value to or null if field is static,fieldName
- field name,valuesString
- comma separated values.ConverterException
- if there is no converter registered for field component type or parsing fails.BugError
- if named field type is not of supported types.public static String getPackageResource(Class<?> type, String resourceName)
pdf-view-fop.xconf
and class js.fop.PdfView
this method returns
js/fop/pdf-view-fop.xconf
.type
- class to infer package on which resource reside,resourceName
- simple resource name.public static URL getResource(String name)
Resource is searched into next class loaders, in given order:
ClassLoader.getSystemClassLoader()
name
- resource qualified name, using path separators instead of dots.IllegalArgumentException
- if name
argument is null.private static URL getResource(String name, ClassLoader[] classLoaders)
name
- resource name with syntax as requested by Java ClassLoader,classLoaders
- target class loaders.public static InputStream getResourceAsStream(String name)
ClassLoader.getResourceAsStream(String)
and
name
argument should follow Java class loader convention: it is always considered as absolute path,
that is, should contain package but does not start with leading path separator, e.g. js/fop/config.xml
.
Resource is searched into next class loaders, in given order:
ClassLoader.getSystemClassLoader()
name
- resource qualified name, using path separators instead of dots.IllegalArgumentException
- if name
argument is null or empty.NoSuchBeingException
- if resource not found.private static InputStream getResourceAsStream(String name, ClassLoader[] classLoaders)
name
- resource name with syntax as required by Java ClassLoader,classLoaders
- target class loaders.public static File getResourceAsFile(String name)
File
otherwise throws unsupported
operation.name
- resource name.NoSuchBeingException
- if named resource can't be loaded.UnsupportedOperationException
- if named resource protocol is not file.public static Reader getResourceAsReader(String name) throws UnsupportedEncodingException
getResourceAsStream(String)
and return the
stream wrapped into a reader.name
- resource name.UnsupportedEncodingException
- if Java run-time does not support UTF-8 encoding.NoSuchBeingException
- if resource not found.public static String getResourceAsString(String name) throws IOException
getResourceAsReader(String)
to reader resource content
and store it in a String.name
- resource name.NoSuchBeingException
- if resource not found.IOException
- if resource reading fails.public static byte[] getResourceAsBytes(String name) throws IOException
getResourceAsStream(String)
to read binary resource and
return bytes array.name
- resource name.NoSuchBeingException
- if resource not found.IOException
- if resource reading fails.public static Collection<String> listPackageResources(String packageName, String fileNamesPattern)
ClassLoader.getResources(String)
. If returned URL starts with jar:file
, that is,
has JAR protocol the package is contained into a Java archive file and is processed entry by entry. Otherwise
protocol should be file
and package is located into local classes and is processed as file. If
protocol is neither file
nor jar:file
throws unsupported operation.packageName
- qualified package name, possible empty for package root,fileNamesPattern
- file names pattern as accepted by FilteredStrings.FilteredStrings(String)
.NoSuchBeingException
- if package is not found by current application class loader.UnsupportedOperationException
- if found package URL protocol is not file
or
jar:file
.private static Collection<String> listPackageResources(URL packageURL, String packagePath, String fileNamesPattern)
file
and jar:file
URL
protocols meaning it searches on both local classes and .jar
files.packageURL
- package URL as returned by ClassLoader.getResources(String)
,packagePath
- package path for resources lookup, possible empty for package root,fileNamesPattern
- file name pattern.UnsupportedOperationException
- given package URL protocol is not file
or jar:file
.public static <T> T newInstance(Type type, Object... arguments)
newInstance(Class, Object...)
,
respective newCollection(Type)
or newMap(Type)
.T
- instance type.type
- instance type.arguments
- constructor arguments.BugError
- if instance cannot be created.public static <T> T newInstance(String className, Object... arguments)
T
- instance type.className
- fully qualified class name,arguments
- variable number of arguments to be passed to constructor.NoSuchBeingException
- if class or constructor not found.public static <T> T newInstance(Class<T> clazz, Object... arguments) throws BugError, NoSuchBeingException, BugError
newCollection(Type)
, newList(Type)
respective newMap(Type)
.
If arguments are supplied a constructor with exact formal parameters is located otherwise default constructor is
used; if none found throws NoSuchBeingException
. This method forces accessibility so is not mandatory for
constructor to be public.
Requested class should be instantiable, i.e. should not be interface, abstract or void class. Also arrays are not accepted by this factory method.
T
- instance type.clazz
- object class to instantiate,arguments
- optional constructor arguments.BugError
- if attempt to instantiate interface, abstract, array or void class.NoSuchBeingException
- if class or constructor not found.BugError
- for any other failing condition, since there is no particular reason to expect fail.InvocationException
- with target exception if constructor fails on its execution.private static NoSuchBeingException missingConstructorException(Class<?> clazz, Object... arguments)
clazz
- constructor class,arguments
- constructor arguments.public static <T extends Collection<?>> T newCollection(Type type)
T
- collection type.type
- collection type.public static <T extends List<?>> Class<T> getListDefaultImplementation(Type listType)
T
- list type.listType
- raw list type.public static <T extends List<?>> T newList(Type type)
T
- list type.type
- list raw type.public static Class<?> getImplementation(Map<Class<?>,Class<?>> implementationsRegistry, Type interfaceType)
implementationsRegistry
- implementations registry,interfaceType
- interface to lookup into registry.BugError
- if implementation is not found into registry.private static <T> T newRegisteredInstance(Map<Class<?>,Class<?>> implementationsRegistry, Type interfaceType) throws BugError
T
- instance type.implementationsRegistry
- implementations registry,interfaceType
- interface to lookup into registry.BugError
- if implementation is not found into registry.public static <T extends Map<?,?>> T newMap(Type type)
T
- map type.type
- map type.public static Class<?> forType(Type type)
type
- the typepublic static <T> T unproxy(T instance)
InstanceInvocationHandler
handler. If given
instance
is not a Java Proxy return it as it is and return null if instance
is null. It
is considered a bug if instance
is a Java Proxy and its handler does not implement
InstanceInvocationHandler
.T
- instance type.instance
- instance to unproxy, null accepted.BugError
- if Java Proxy handler does not implement InstanceInvocationHandler
.Copyright © 2018. All rights reserved.