TUM CCSM Commons

edu.tum.cs.commons.reflect
Class ReflectionUtils

java.lang.Object
  extended by edu.tum.cs.commons.reflect.ReflectionUtils

public class ReflectionUtils
extends java.lang.Object

This class provides utility methods for reflection purposes. In particular it provides access to FormalParameter.

Version:
$Rev: 26268 $
Author:
Florian Deissenboeck, Benjamin Hummel, $Author: juergens $
Rating:
GREEN Hash: AD094410F95DFE6BB4CB12A5DC8A5F27

Constructor Summary
ReflectionUtils()
           
 
Method Summary
static
<T> T
convertString(java.lang.String value, java.lang.Class<T> targetType)
          Convert a String to an Object of the provided type.
static java.util.HashMap<java.lang.String,Version> getClassFileVersions(java.io.File jarFile)
          This method extracts the class file version from each class file in the provided jar.
static FormalParameter[] getFormalParameters(java.lang.reflect.Method method)
          Obtain array of formal parameters for a method.
static java.util.List<java.lang.Class<?>> getSuperClasses(java.lang.Class<?> clazz)
          Get super class list of a class.
static java.lang.Object invoke(java.lang.reflect.Method method, java.lang.Object object, java.util.Map<FormalParameter,java.lang.Object> parameterMap)
          Invoke a method with parameters.
static boolean isAssignable(java.lang.Class<?> source, java.lang.Class<?> target)
          Check whether an Object of the source type can be used instead of an Object of the target type.
static boolean isConvertibleFromString(java.lang.Class<?> targetType)
          This method checks if the provided type can be converted from a string.
static boolean isInstanceOfAll(java.lang.Object o, java.lang.Class<?>... classes)
          Returns whether the given object is an instance of all of the given classes.
static boolean isInstanceOfAny(java.lang.Object o, java.lang.Class<?>... classes)
          Returns whether the given object is an instance of at least one of the given classes.
static
<T> java.util.List<T>
listInstances(java.util.List<?> objects, java.lang.Class<T> type)
          Creates a list that contains only the types that are instances of a specified type from the objects of an input list.
static Version obtainClassFileVersion(java.io.InputStream inputStream)
          Obtains the version of a Java class file.
static java.lang.Class<?> obtainGenericMethodReturnType(java.lang.Class<?> clazz, java.lang.String methodName)
          Obtain the generic return type of method.
static java.lang.Class<?> obtainMethodReturnType(java.lang.Class<?> clazz, java.lang.String methodName)
          Obtain the return type of method.
static
<T> T
performNearestClassLookup(java.lang.Class<?> clazz, java.util.Map<java.lang.Class<?>,T> classMap)
          Returns the value from the map, whose key is the best match for the given class.
static
<T> T
pickInstanceOf(java.lang.Class<T> clazz, java.util.Collection<?> objects)
          Returns the first object in the given collection which is an instance of the given class (or null otherwise).
static java.lang.Class<?> resolvePrimitiveClass(java.lang.Class<?> clazz)
          Returns the wrapper class type for a primitive type (e.g.
static java.lang.Class<?> resolveType(java.lang.String typeName)
          Resolves the class object for a type name.
static java.lang.Class<?> resolveType(java.lang.String typeName, java.lang.ClassLoader classLoader)
          Resolves the class object for a type name.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ReflectionUtils

public ReflectionUtils()
Method Detail

convertString

public static <T> T convertString(java.lang.String value,
                                  java.lang.Class<T> targetType)
                       throws TypeConversionException
Convert a String to an Object of the provided type. It supports conversion to primitive types and simple tests (char: use first character of string, boolean: test for values "true", "on", "1", "yes"). Enums are handled by the EnumUtils.valueOfIgnoreCase(Class, String) method. Otherwise it is checked if the target type has a constructor that takes a single string and it is invoked. For all other cases an exception is thrown, as no conversion is possible. Maintainer note: Make sure this method is changed in accordance with method isConvertibleFromString(Class)

Parameters:
value - the string to be converted.
targetType - the type of the resulting object.
Returns:
the converted object.
Throws:
TypeConversionException - in the case that no conversion could be performed.
See Also:
convertString(String, Class), isConvertibleFromString(Class)

isConvertibleFromString

public static boolean isConvertibleFromString(java.lang.Class<?> targetType)
This method checks if the provided type can be converted from a string. With respect to convertString(String, Class) the semantics are the following: If this method returns true a particular string may be convertible to the target type. If this method returns false, a call to convertString(String, Class) is guaranteed to result in a TypeConversionException. If a call to convertString(String, Class) does not result in an exception, a call to this method is guaranteed to return true.

Maintainer note: Make sure this method is change in accordance with method convertString(String, Class)

See Also:
convertString(String, Class)

getFormalParameters

public static FormalParameter[] getFormalParameters(java.lang.reflect.Method method)
Obtain array of formal parameters for a method.

See Also:
FormalParameter

getSuperClasses

public static java.util.List<java.lang.Class<?>> getSuperClasses(java.lang.Class<?> clazz)
Get super class list of a class.

Parameters:
clazz - the class to start traversal from
Returns:
a list of super class where the direct super class of the provided class is the first member of the list.
For Object, primitives and interfaces this returns an empty list.
For arrays this returns a list containing only Object.
For enums this returns a list containing Enum and Object

invoke

public static java.lang.Object invoke(java.lang.reflect.Method method,
                                      java.lang.Object object,
                                      java.util.Map<FormalParameter,java.lang.Object> parameterMap)
                               throws java.lang.IllegalArgumentException,
                                      java.lang.IllegalAccessException,
                                      java.lang.reflect.InvocationTargetException
Invoke a method with parameters.

Parameters:
method - the method to invoke
object - the object the underlying method is invoked from
parameterMap - this maps from the formal parameter of the method to the parameter value
Returns:
the result of dispatching the method
Throws:
java.lang.IllegalArgumentException - if the method is an instance method and the specified object argument is not an instance of the class or interface declaring the underlying method (or of a subclass or implementor thereof); if the number of actual and formal parameters differ; if an unwrapping conversion for primitive arguments fails; or if, after possible unwrapping, a parameter value cannot be converted to the corresponding formal parameter type by a method invocation conversion; if formal parameters belong to different methods.
java.lang.IllegalAccessException - if this Method object enforces Java language access control and the underlying method is inaccessible.
java.lang.reflect.InvocationTargetException - if the underlying method throws an exception.
java.lang.NullPointerException - if the specified object is null and the method is an instance method.
java.lang.ExceptionInInitializerError - if the initialization provoked by this method fails.

isAssignable

public static boolean isAssignable(java.lang.Class<?> source,
                                   java.lang.Class<?> target)
Check whether an Object of the source type can be used instead of an Object of the target type. This method is required, as the Class.isAssignableFrom(java.lang.Class) does not handle primitive types.

Parameters:
source - type of the source object
target - type of the target object
Returns:
whether an assignment would be possible.

resolvePrimitiveClass

public static java.lang.Class<?> resolvePrimitiveClass(java.lang.Class<?> clazz)
Returns the wrapper class type for a primitive type (e.g. Integer for an int). If the given class is not a primitive, the class itself is returned.

Parameters:
clazz - the class.
Returns:
the corresponding class type.

resolveType

public static java.lang.Class<?> resolveType(java.lang.String typeName)
                                      throws java.lang.ClassNotFoundException
Resolves the class object for a type name. Type name can be a primitive. For resolution, Class.forName(String) is used, that uses the caller's class loader.

While method Class.forName(...) resolves fully qualified names, it does not resolve primitives, e.g. "java.lang.Boolean" can be resolved but "boolean" cannot.

Parameters:
typeName - name of the type. For primitives case is ignored.
Throws:
java.lang.ClassNotFoundException - if the typeName neither resolves to a primitive, nor to a known class.

resolveType

public static java.lang.Class<?> resolveType(java.lang.String typeName,
                                             java.lang.ClassLoader classLoader)
                                      throws java.lang.ClassNotFoundException
Resolves the class object for a type name. Type name can be a primitive. For resolution, the given class loader is used.

While method Class.forName(...) resolves fully qualified names, it does not resolve primitives, e.g. "java.lang.Boolean" can be resolved but "boolean" cannot.

Parameters:
typeName - name of the type. For primitives case is ignored.
classLoader - the class loader used for loading the class. If this is null, the caller class loader is used.
Throws:
java.lang.ClassNotFoundException - if the typeName neither resolves to a primitive, nor to a known class.

obtainMethodReturnType

public static java.lang.Class<?> obtainMethodReturnType(java.lang.Class<?> clazz,
                                                        java.lang.String methodName)
                                                 throws java.lang.NoSuchMethodException
Obtain the return type of method. This method deals with bridge methods introduced by generics. This works for methods without parameters only.

Parameters:
clazz - the class
methodName - the name of the method.
Returns:
the return type
Throws:
java.lang.NoSuchMethodException - if the class doesn't contain the desired method

obtainGenericMethodReturnType

public static java.lang.Class<?> obtainGenericMethodReturnType(java.lang.Class<?> clazz,
                                                               java.lang.String methodName)
                                                        throws java.lang.NoSuchMethodException
Obtain the generic return type of method. This method deals with the gory details of bridge methods and generics. This works for methods without parameters only. This doesn't work for interfaces, arrays and enums.

Parameters:
clazz - the class
methodName - the name of the method.
Returns:
the return type
Throws:
java.lang.NoSuchMethodException - if the class doesn't contain the desired method

performNearestClassLookup

public static <T> T performNearestClassLookup(java.lang.Class<?> clazz,
                                              java.util.Map<java.lang.Class<?>,T> classMap)
Returns the value from the map, whose key is the best match for the given class. The best match is defined by the first match occurring in a breath first search of the inheritance tree, where the base class is always visited before the implemented interfaces. Interfaces are traversed in the order they are defined in the source file. The only exception is Object, which is considered only as the very last option.

As this lookup can be expensive (reflective iteration over the entire inheritance tree) the results should be cached if multiple lookups for the same class are expected.

Parameters:
clazz - the class being looked up.
classMap - the map to perform the lookup in.
Returns:
the best match found or null if no matching entry was found. Note that null will also be returned if the entry for the best matching class was null.

isInstanceOfAny

public static boolean isInstanceOfAny(java.lang.Object o,
                                      java.lang.Class<?>... classes)
Returns whether the given object is an instance of at least one of the given classes.


isInstanceOfAll

public static boolean isInstanceOfAll(java.lang.Object o,
                                      java.lang.Class<?>... classes)
Returns whether the given object is an instance of all of the given classes.


pickInstanceOf

public static <T> T pickInstanceOf(java.lang.Class<T> clazz,
                                   java.util.Collection<?> objects)
Returns the first object in the given collection which is an instance of the given class (or null otherwise).


obtainClassFileVersion

public static Version obtainClassFileVersion(java.io.InputStream inputStream)
                                      throws java.io.IOException
Obtains the version of a Java class file. Class file versions (from http://thiamteck.blogspot.com/2007/11/determine- java-class-file-version.html):
 major  minor      Java Version 
        45       3           1.0
        45       3           1.1
        46       0           1.2
        47       0           1.3
        48       0           1.4
        49       0           1.5
        50       0           1.6
 

Parameters:
inputStream - stream to read class file from.
Returns:
the class file version or null if stream does not contain a class file.
Throws:
java.io.IOException - if an IO problem occurs.

getClassFileVersions

public static java.util.HashMap<java.lang.String,Version> getClassFileVersions(java.io.File jarFile)
                                                                        throws java.io.IOException
This method extracts the class file version from each class file in the provided jar.

Returns:
the result maps from the class file to its version.
Throws:
java.io.IOException

listInstances

public static <T> java.util.List<T> listInstances(java.util.List<?> objects,
                                                  java.lang.Class<T> type)
Creates a list that contains only the types that are instances of a specified type from the objects of an input list. The input list is not modified.

Parameters:
objects - List of objects that gets filtered
type - target type whose instances are returned

TUM CCSM Commons

TUM CCSM Commons - 2.7