Retrieving class
Class.forName(str)
will return the class with the given name. You must pass the fully qualified name, like "org.example.MyTestSuite". In other use cases where you want to create another instance of a given object, you can just call Object#getClass()
.
Constructors and Instantiation
You can get all constructor with Class#getConstructors()
, so that you could check if a nullary constructor (without parameters) is available. Class#newInstance()
will try to create an instance with the nullary constructor and throw an IllegalAccessException if none is available. Constructors with parameters can be invoked with Constructor#newInstance(Object...)
.
Methods
A class' methods will be listed with Class#getDeclaredMethods()
. For further examination Method#getGenericParameterTypes()
returns the parameters' classes. You can even make private methods invokable by using Method#setAccessible(true)
. Then finally Method#invoke(Class)
executes the method on the given class instance. Use Method#invoke(Class, Object...)
for methods with arguments, whereas the var-args represents the arguments.
Example
The Java Documentation contains some good examples, I modified one a little bit for your use case:
try {
// retrieving class
Class<?> c = Class.forName(str);
// will throw IllegalAccessException if the class
// or its nullary constructor is not accessible:
Object t = c.newInstance();
Method[] allMethods = c.getDeclaredMethods();
for (Method m : allMethods) {
String mname = m.getName();
// run only test methods
if (!mname.startsWith("test")) {
continue;
}
Type[] pType = m.getGenericParameterTypes();
if (pType.length != 0) {
throw new RuntimeException("Test methods must not have parameters.");
}
try {
// you can call private methods by setting this flag
m.setAccessible(true);
// invoking method m of instance t
m.invoke(t);
} catch (InvocationTargetException x) {
// Handle any exceptions thrown by method to be invoked.
Throwable cause = x.getCause();
err.format("invocation of %s failed: %s%n",
mname, cause.getMessage());
}
}
// production code should handle these exceptions more gracefully
} catch (ClassNotFoundException x) {
x.printStackTrace();
} catch (InstantiationException x) {
x.printStackTrace();
} catch (IllegalAccessException x) {
x.printStackTrace();
}