How to call a function whose name is stored in a string variable

The objective is simple, create a method which load a class dynamically, access its method and passing their parameters value and getting the return value at run-time. To do that is possible to use Java reflection.

try {
	Class<?> clazz = Class.forName("package.myclass");
	Method mth = clazz.getDeclaredMethod("method", String.class, String.class);
	Object source_class = clazz.newInstance(); 
}
catch (SecurityException ex) {				
	return null;
}
catch (NoSuchMethodException ex) {
	return null;
}
catch (IllegalArgumentException ex) {
	return null;
} 
catch (IllegalAccessException ex) {
	return null;
} 
catch (InvocationTargetException ex) {
	return null;
}
 
logger.debug((String) mth.invoke(source_class, "Param1", "Test ${medicationGenericName}"));

In this case the method needs two string as parameter and returns a string.

If the constructor of the class needs a parameter (i.e. the application context because the @Autowired doesn’t works), this is the code needed:

Class<?> clazz = Class.forName("package.myclass");
Constructor <?> constructor = clazz.getDeclaredConstructor(ApplicationContext.class);
Method mth = clazz.getDeclaredMethod("method", String.class, String.class);				
Object source_class = constructor.newInstance(applicationContext);
Tagged

Leave a Reply