Constructor[] c = aClass.getConstructors(); // Retrieve all the constructors
// of the class 'aClass'
for (Constructor constructor : c) { // Iterate all constructors
// Until the only default constructor is found.
if (constructor.getParameterTypes().length == 0) {
// Create a new instance of 'aClass' using the default constructor
// Hope that 'aClass' implements 'AInterface' otherwise ClassCastException ...
AInterface action = (AInterface) constructor.newInstance();
try {
// action has been cast to AInterface - so it can be used to call the run method
// defined on the AInterface interface.
action.run(request, response);
} // Oops - missing catch and/or finally. That won't compile
}
}
// Missing a bit of error handling here for the countless reflection exception
// Unless the method is declared as 'throws Exception' or similar
Example of usage:
You have a class somewhere called 'TheClass'
public class TheClass implements AInterface {
public void run(HttpServletRequest request, HttpServletResponse response) {
System.out.println("Hello from TheClass.run(...)");
// Implement the method ...
}
}
Somewhere in the application, either using Reflection or reading a Configuration file.
The application finds out that it should execute 'TheClass'.
You do not have any indication about 'TheClass' other that it should implement AInterface and it has an default constructor.
You can create the Class object using
Class aClass = Class.forName("TheClass");
and use 'aClass' in you previous code snippet (after adding the code for errorhandling). You should see in the console
Hello from TheClass.run(...)