public class ReflectionSupport extends Object
Consider a situation where you are writing a test case that invokes the
doIt()
method on a given object. You might do it like
this:
MyType result = receiver.doIt(param1, param2); // returns a value // ... receiver.doSomethingElse(); // a void method with no parameters
The first line passes two parameters to doIt()
and stores
the return value in a local variable called result
. All
this would be fine if the class under test actually provides a method
called doIt()
with the appropriate signature and return
type. Otherwise, you would get a compile-time error. But on Web-CAT
a compilation error in a test suite would give a resulting score of
zero--no successful compilation, no partial credit. The story is similar
with the second line, which simply calls a void method on the class
under test.
What if, instead, you wanted to write test cases that checked for specific methods, and either succeeded or failed depending on whether the method was present? You can use the methods in this class to write such test cases. So instead of writing the call above, you could do this:
// At the top of your test class import static net.sf.webcat.ReflectionSupport.*; // ... // For a method that returns a result: MyType result = invoke(receiver, MyType.class, "doIt", param1, param2); // Or for a void method: invoke(receiver, "doSomethingElse");
The syntax is simple and straight forward. The overloaded invoke method can be used on functions (methods that return a value) or procedures (void methods that return nothing). For methods that return a value, you specify the type of the return value as the second parameter. If you omit the return type, then it is assumed to be "void". You specify the name of the method as a string, and then a variable length set of arguments.
If you are calling a method that is returning a primitive type, be sure to use the corresponding wrapper class as the expected return value:
// Instead of boolean answer = receiver.equals(anotherObject); Boolean answer = invoke(receiver, Boolean.class, "equals", anotherObject); // Or in an assert, using auto-unboxing: assertTrue(invoke(receiver, Boolean.class, "equals", anotherObject));
Any errors that occur during reflection, such as failing to find the required method, failing to find a method with the required signature, finding a method that is not public, etc., are converted into appropriate test case errors with meaningful diagnostic hints for the student. Any exceptions are wrapped in a RuntimeException and need not be explicitly caught by the caller (they will turn into test case failures as well).
Modifier and Type | Class and Description |
---|---|
static class |
ReflectionSupport.NonDeferringClassLoader
A custom class loader used when supporting forced re-loading of
classes that contain statics that should be re-evaluated/re-
initialized fresh.
|
static class |
ReflectionSupport.ParameterAcceptanceCategory
An enumeration that represents the different categories of
parameter matching possible between a method and possible
parameters.
|
static class |
ReflectionSupport.ParameterConversionCategory
An enumeration that represents the different kinds of conversions
supported for method invocation conversions (see JLS Section 5.3).
|
static class |
ReflectionSupport.ParameterSignature
This class only represents the parameter list signature for a
method as a list of Class values.
|
static class |
ReflectionSupport.ReflectionError
A custom error class that represents any error conditions that
arise in the reflection-based methods provided by this class.
|
static class |
ReflectionSupport.VisibilityConstraint
An enumeration that represents a set of constants for specifying
constraints on the visibility of a declaration.
|
Modifier and Type | Method and Description |
---|---|
static boolean |
actualMatchesFormal(Class<?> actual,
Class<?> formal)
Determine whether an actual argument type matches a formal argument
type, based on the rules of JLS Section 5.3.
|
static ReflectionSupport.ParameterConversionCategory |
canCoerceFromActualToFormal(Class<?> actual,
Class<?> formal)
Determine the type of method invocation conversion, if any, Java would
apply to convert from an actual argument of type
actual
into a formal parameter type formal , possibly including
"auto-boxing" or "auto-unboxing", widening primitive conversions, or
widening reference conversions, according to the rules of JLS Section
5.3. |
static <T> T |
create(Class<T> returnType,
Object... params)
Dynamically look up and invoke a class constructor for the target
class, with appropriate hints if any failures happen along the way.
|
static <T> T |
create(Constructor<T> constructor,
Object... params)
Just like
Constructor.newInstance(Object...) , but converts
any thrown exceptions into RuntimeExceptions. |
static Object |
create(String className,
Object... params)
Dynamically look up and invoke a class constructor for the target
class, with appropriate hints if any failures happen along the way.
|
static <T> T |
createEx(Class<T> returnType,
Object... params)
Just like
create(Class, Object...) , but unwraps
any InvocationTargetExceptions and throws the true cause. |
static Object |
createEx(Constructor<?> constructor,
Object... params)
Just like
create(Constructor, Object...) , but unwraps
any InvocationTargetExceptions and throws the true cause. |
static Object |
createEx(String className,
Object... params)
Just like
create(String, Object...) , but unwraps
any InvocationTargetExceptions and throws the true cause. |
static <T> T |
get(Class<?> receiverClass,
Class<T> type,
String fieldName)
Get the value of a field.
|
static <T> T |
get(Object receiver,
Class<T> type,
String fieldName)
Get the value of a field.
|
static Class<?> |
getClassForName(String... classNames)
Dynamically look up a class by name using a sequence of one or more
potential class names, with appropriate hints if the class cannot be
found.
|
static Class<?> |
getClassForName(String className,
ClassLoader loader)
Dynamically look up a class by name, with appropriate hints if the
class cannot be found.
|
static Class<?> |
getClassForNameIfPossible(String className,
ClassLoader loader)
Dynamically look up a class by name, returning null if the class
is not found.
|
static Field |
getField(Class<?> receiverClass,
Class<?> type,
String fieldName)
Look up a field by name, receiver class, and type, finding the
field that will accept the given type (not requiring
an exact match on type).
|
static Constructor<?> |
getMatchingConstructor(Class<?> c,
Class<?>... params)
Look up a constructor by parameter profile, finding the
constructor that will accept the given list of parameters (not
requiring an exact match on parameter types).
|
static Constructor<?> |
getMatchingConstructor(Class<?> c,
ReflectionSupport.ParameterSignature params)
Look up a constructor by parameter profile, finding the
constructor that will accept the given list of parameters (not
requiring an exact match on parameter types).
|
static Constructor<?> |
getMatchingConstructor(Class<?> c,
ReflectionSupport.VisibilityConstraint visibility,
Class<?>... params)
Look up a constructor by parameter profile, finding the
constructor that will accept the given list of parameters (not
requiring an exact match on parameter types).
|
static Constructor<?> |
getMatchingConstructor(Class<?> c,
ReflectionSupport.VisibilityConstraint visibility,
ReflectionSupport.ParameterSignature params)
Look up a constructor by parameter profile, finding the
constructor that will accept the given list of parameters (not
requiring an exact match on parameter types).
|
static Method |
getMatchingMethod(Class<?> c,
ReflectionSupport.VisibilityConstraint visibility,
String name,
Class<?>... params)
Look up a method by name and parameter profile, finding the
method that will accept the given list of parameters (not requiring
an exact match on parameter types).
|
static Method |
getMatchingMethod(Class<?> c,
ReflectionSupport.VisibilityConstraint visibility,
String name,
ReflectionSupport.ParameterSignature params)
Look up a method by name and parameter profile, finding the
method that will accept the given list of parameters (not requiring
an exact match on parameter types).
|
static Method |
getMatchingMethod(Class<?> c,
String name,
Class<?>... params)
Look up a method by name and parameter profile, finding the
method that will accept the given list of parameters (not requiring
an exact match on parameter types).
|
static Method |
getMatchingMethod(Class<?> c,
String name,
ReflectionSupport.ParameterSignature params)
Look up a method by name and parameter profile, finding the
method that will accept the given list of parameters (not requiring
an exact match on parameter types).
|
static Method |
getMethod(Class<?> c,
ReflectionSupport.VisibilityConstraint visibility,
String name,
Class<?>... params)
Look up a method by name and parameter profile, turning any
errors into test case failures with appropriate hint messages.
|
static Method |
getMethod(Class<?> c,
String name,
Class<?>... params)
Look up a method by name and parameter profile, turning any
errors into test case failures with appropriate hint messages.
|
static <T> T |
invoke(Object receiver,
Class<T> returnType,
String methodName,
Object... params)
Dynamically look up and invoke a method on a target object, with
appropriate hints if any failures happen along the way.
|
static Object |
invoke(Object receiver,
Method method,
Object... params)
Just like
Method.invoke(Object, Object...) , but converts
any thrown exceptions into RuntimeExceptions. |
static <T> T |
invoke(Object receiver,
ReflectionSupport.VisibilityConstraint visibility,
Class<T> returnType,
String methodName,
Object... params)
Dynamically look up and invoke a method on a target object, with
appropriate hints if any failures happen along the way.
|
static void |
invoke(Object receiver,
ReflectionSupport.VisibilityConstraint visibility,
String methodName,
Object... params)
Dynamically look up and invoke a method on a target object, with
appropriate hints if any failures happen along the way.
|
static void |
invoke(Object receiver,
String methodName,
Object... params)
Dynamically look up and invoke a method on a target object, with
appropriate hints if any failures happen along the way.
|
static <T> T |
invokeEx(Object receiver,
Class<T> returnType,
String methodName,
Object... params)
Just like
invoke(Object, Class, String, Object...) , but unwraps
any InvocationTargetExceptions and throws the true cause. |
static Object |
invokeEx(Object receiver,
Method method,
Object... params)
Just like
Method.invoke(Object, Object...) , but unwraps
any InvocationTargetExceptions and throws the true cause. |
static <T> T |
invokeEx(Object receiver,
ReflectionSupport.VisibilityConstraint visibility,
Class<T> returnType,
String methodName,
Object... params)
Just like
invoke(Object, Class, String, Object...) , but unwraps
any InvocationTargetExceptions and throws the true cause. |
static void |
invokeEx(Object receiver,
ReflectionSupport.VisibilityConstraint visibility,
String methodName,
Object... params)
Just like
invoke(Object, String, Object...) , but unwraps
any InvocationTargetExceptions and throws the true cause. |
static void |
invokeEx(Object receiver,
String methodName,
Object... params)
Just like
invoke(Object, String, Object...) , but unwraps
any InvocationTargetExceptions and throws the true cause. |
static Class<?> |
reloadClassForName(String... classNames)
Dynamically look up a class by name using a sequence of one or more
potential class names, with appropriate hints if the class cannot be
found.
|
static void |
set(Class<?> receiverClass,
String fieldName,
Object value)
Sets value of a field.
|
static void |
set(Object receiver,
String fieldName,
Object value)
Sets value of a field.
|
static String |
simpleArgumentList(Class<?>... params)
Constructs a printable version of a method's argument list, including
the parentheses, given the method's parameter type(s), if any.
|
static String |
simpleClassName(Class<?> aClass)
Returns the name of the given class without any package prefix.
|
static String |
simpleClassNameUsingPrimitives(Class<?> aClass)
Returns the name of the given class without any package prefix.
|
static String |
simpleMethodName(Method method)
Constructs a printable version of a method's name.
|
static String |
simpleMethodName(String name,
Class<?>... params)
Constructs a printable version of a method's name, given
the method name and its parameter type(s), if any.
|
static String |
simpleMethodName(String name,
ReflectionSupport.ParameterSignature params)
Constructs a printable version of a method's name, given
the method name and its parameter type(s), if any.
|
public static Class<?> getClassForNameIfPossible(String className, ClassLoader loader)
className
- The name of the class to find.loader
- The class loader to search from.public static Class<?> getClassForName(String className, ClassLoader loader)
className
- The name of the class to find.loader
- The class loader to search from.public static Class<?> getClassForName(String... classNames)
classNames
- The sequence of class names to look for.public static Class<?> reloadClassForName(String... classNames)
classNames
- The sequence of class names to look for.public static Constructor<?> getMatchingConstructor(Class<?> c, Class<?>... params)
c
- The type of object to createparams
- The constructor's parameter profilepublic static Constructor<?> getMatchingConstructor(Class<?> c, ReflectionSupport.ParameterSignature params)
c
- The type of object to createparams
- The constructor's parameter profilepublic static Constructor<?> getMatchingConstructor(Class<?> c, ReflectionSupport.VisibilityConstraint visibility, Class<?>... params)
c
- The type of object to createvisibility
- The required visibility of the methodparams
- The constructor's parameter profilepublic static Constructor<?> getMatchingConstructor(Class<?> c, ReflectionSupport.VisibilityConstraint visibility, ReflectionSupport.ParameterSignature params)
c
- The type of object to createvisibility
- The required visibility of the methodparams
- The constructor's parameter profilepublic static <T> T create(Constructor<T> constructor, Object... params)
Constructor.newInstance(Object...)
, but converts
any thrown exceptions into RuntimeExceptions.T
- The generic parameter T is deduced from the provided
constructorconstructor
- The constructor to invokeparams
- The parameters to pass to the constructorpublic static <T> T create(Class<T> returnType, Object... params)
T
- The generic parameter T is deduced from the returnTypereturnType
- The type of object to create.params
- The parameters to pass to the constructorpublic static Object create(String className, Object... params)
className
- The type of object to createparams
- The parameters to pass to the constructorpublic static Object createEx(Constructor<?> constructor, Object... params) throws Exception
create(Constructor, Object...)
, but unwraps
any InvocationTargetExceptions and throws the true cause. This
version is provided when you want to write test cases where you
are intending to check for Exceptions as expected results.constructor
- The constructor to invokeparams
- The parameters to pass to the constructorException
- if the underlying method throws onepublic static <T> T createEx(Class<T> returnType, Object... params) throws Exception
create(Class, Object...)
, but unwraps
any InvocationTargetExceptions and throws the true cause. This
version is provided when you want to write test cases where you
are intending to check for Exceptions as expected results.T
- The generic parameter T is deduced from the returnTypereturnType
- The type of object to create.params
- The parameters to pass to the constructorException
- if the underlying method throws onepublic static Object createEx(String className, Object... params) throws Exception
create(String, Object...)
, but unwraps
any InvocationTargetExceptions and throws the true cause. This
version is provided when you want to write test cases where you
are intending to check for Exceptions as expected results.className
- The type of object to createparams
- The parameters to pass to the constructorException
- if the underlying method throws onepublic static Method getMethod(Class<?> c, String name, Class<?>... params)
c
- The type of the receivername
- The method nameparams
- The method's parameter profilepublic static Method getMethod(Class<?> c, ReflectionSupport.VisibilityConstraint visibility, String name, Class<?>... params)
c
- The type of the receivervisibility
- The required visibility of the methodname
- The method nameparams
- The method's parameter profilepublic static Method getMatchingMethod(Class<?> c, String name, Class<?>... params)
c
- The type of the receivername
- The method nameparams
- The method's parameter profilepublic static Method getMatchingMethod(Class<?> c, String name, ReflectionSupport.ParameterSignature params)
c
- The type of the receivername
- The method nameparams
- The method's parameter profilepublic static Method getMatchingMethod(Class<?> c, ReflectionSupport.VisibilityConstraint visibility, String name, Class<?>... params)
c
- The type of the receivervisibility
- The required visibility of the methodname
- The method nameparams
- The method's parameter profilepublic static Method getMatchingMethod(Class<?> c, ReflectionSupport.VisibilityConstraint visibility, String name, ReflectionSupport.ParameterSignature params)
c
- The type of the receivervisibility
- The required visibility of the methodname
- The method nameparams
- The method's parameter profilepublic static <T> T invoke(Object receiver, Class<T> returnType, String methodName, Object... params)
T
- The generic parameter T is deduced from the returnTypereceiver
- The object to invoke the method onreturnType
- The expected type of the method's return value.
Use null (or void.class
) if the method that is
looked up is a void method.methodName
- The name of the method to invokeparams
- The parameters to pass to the methodpublic static <T> T invoke(Object receiver, ReflectionSupport.VisibilityConstraint visibility, Class<T> returnType, String methodName, Object... params)
T
- The generic parameter T is deduced from the returnTypereceiver
- The object to invoke the method onvisibility
- The required visibility of the methodreturnType
- The expected type of the method's return value.
Use null (or void.class
) if the method that is
looked up is a void method.methodName
- The name of the method to invokeparams
- The parameters to pass to the methodpublic static void invoke(Object receiver, String methodName, Object... params)
receiver
- The object to invoke the method onmethodName
- The name of the method to invokeparams
- The parameters to pass to the methodpublic static void invoke(Object receiver, ReflectionSupport.VisibilityConstraint visibility, String methodName, Object... params)
receiver
- The object to invoke the method onvisibility
- The required visibility of the methodmethodName
- The name of the method to invokeparams
- The parameters to pass to the methodpublic static Object invoke(Object receiver, Method method, Object... params)
Method.invoke(Object, Object...)
, but converts
any thrown exceptions into RuntimeExceptions.receiver
- The object to invoke the method onmethod
- The method to invokeparams
- The parameters to pass to the methodpublic static <T> T invokeEx(Object receiver, Class<T> returnType, String methodName, Object... params) throws Exception
invoke(Object, Class, String, Object...)
, but unwraps
any InvocationTargetExceptions and throws the true cause. This
version is provided when you want to write test cases where you
are intending to check for Exceptions as expected results.T
- The generic parameter T is deduced from the returnTypereceiver
- The object to invoke the method onreturnType
- The expected type of the method's return value.
Use null (or void.class
) if the method that is
looked up is a void method.methodName
- The name of the method to invokeparams
- The parameters to pass to the methodException
- if the underlying method throws onepublic static <T> T invokeEx(Object receiver, ReflectionSupport.VisibilityConstraint visibility, Class<T> returnType, String methodName, Object... params) throws Exception
invoke(Object, Class, String, Object...)
, but unwraps
any InvocationTargetExceptions and throws the true cause. This
version is provided when you want to write test cases where you
are intending to check for Exceptions as expected results.T
- The generic parameter T is deduced from the returnTypereceiver
- The object to invoke the method onvisibility
- The required visibility of the methodreturnType
- The expected type of the method's return value.
Use null (or void.class
) if the method that is
looked up is a void method.methodName
- The name of the method to invokeparams
- The parameters to pass to the methodException
- if the underlying method throws onepublic static void invokeEx(Object receiver, String methodName, Object... params) throws Exception
invoke(Object, String, Object...)
, but unwraps
any InvocationTargetExceptions and throws the true cause. This
version is provided when you want to write test cases where you
are intending to check for Exceptions as expected results.receiver
- The object to invoke the method onmethodName
- The name of the method to invokeparams
- The parameters to pass to the methodException
- if the underlying method throws onepublic static void invokeEx(Object receiver, ReflectionSupport.VisibilityConstraint visibility, String methodName, Object... params) throws Exception
invoke(Object, String, Object...)
, but unwraps
any InvocationTargetExceptions and throws the true cause. This
version is provided when you want to write test cases where you
are intending to check for Exceptions as expected results.receiver
- The object to invoke the method onvisibility
- The required visibility of the methodmethodName
- The name of the method to invokeparams
- The parameters to pass to the methodException
- if the underlying method throws onepublic static Object invokeEx(Object receiver, Method method, Object... params) throws Exception
Method.invoke(Object, Object...)
, but unwraps
any InvocationTargetExceptions and throws the true cause. This
version is provided when you want to write test cases where you
are intending to check for Exceptions as expected results.receiver
- The object to invoke the method onmethod
- The method to invokeparams
- The parameters to pass to the methodException
- if the underlying method throws onepublic static Field getField(Class<?> receiverClass, Class<?> type, String fieldName)
ReflectionSupport.ReflectionError
.
It looks up fields that are declared in the specified class,
as well as inherited classes. It sets up accessibility if the field
is not public.receiverClass
- The class of the receivertype
- The type of this fieldfieldName
- The name of the fieldpublic static <T> T get(Object receiver, Class<T> type, String fieldName)
T
- The generic parameter T is deduced from the returnTypereceiver
- The object containing the fieldtype
- The type of this fieldfieldName
- The name of the fieldpublic static <T> T get(Class<?> receiverClass, Class<T> type, String fieldName)
T
- The generic parameter T is deduced from the returnTypereceiverClass
- The class of the receivertype
- The type of this fieldfieldName
- The name of the fieldpublic static void set(Object receiver, String fieldName, Object value)
receiver
- The object of the receiverfieldName
- The name of the fieldvalue
- The value to set in the fieldpublic static void set(Class<?> receiverClass, String fieldName, Object value)
receiverClass
- The class of the receiverfieldName
- The name of the fieldvalue
- The value will be set in the fieldpublic static String simpleClassName(Class<?> aClass)
aClass
- The class to generate a name forpublic static String simpleClassNameUsingPrimitives(Class<?> aClass)
aClass
- The class to generate a name forpublic static String simpleMethodName(String name, Class<?>... params)
name
- The method nameparams
- The method's parameter type(s), in orderpublic static String simpleMethodName(String name, ReflectionSupport.ParameterSignature params)
name
- The method nameparams
- The method's parameter type(s), in orderpublic static String simpleArgumentList(Class<?>... params)
params
- The method's parameter type(s), in ordersimpleClassName(Class)
, like "(String, int)"public static String simpleMethodName(Method method)
Method.toString()
, this one uses simpleClassName(Class)
so package info is eliminated from the types in the resulting
string. It also omits exception information, unlike Method.toString().method
- The method to printpublic static boolean actualMatchesFormal(Class<?> actual, Class<?> formal)
actual
- The type of the actual parameterformal
- The type of the formal parameterpublic static ReflectionSupport.ParameterConversionCategory canCoerceFromActualToFormal(Class<?> actual, Class<?> formal)
actual
into a formal parameter type formal
, possibly including
"auto-boxing" or "auto-unboxing", widening primitive conversions, or
widening reference conversions, according to the rules of JLS Section
5.3.actual
- The type of the actual value.formal
- The type of the formal parameter.