What's Going On in There? Java Reflection for Program Insight
Using Reflection to Execute Class Methods at Runtime
Suppose you have a class and want to use it at runtime. The code below shows how you can load the class and execute a desired method at runtime. The assumption here is that the method's name is setProperties and it takes an argument of type java.util.Properties.Class newClass = null; Method getInstanceMethod = null; Properties prop = new Properties(); prop.put("argName", "argValue"); try { Object obj = newClass.newInstance(); getInstanceMethod = newClass.getMethod("setProperties",These utilities allow an IDE developer to accommodate Java as a supported programming language quite easily.
new Class[]{new Properties().getClass()}); } catch (Exception ex) { //Exception in loading Class:" + ex.getMessage(); }
A Word of Caution
You have seen the advantages of using the Java Reflection API, but you must understand the disadvantages of reflection as well. For example, debugging will be a nightmare if you don't understand the process well. It is best to use reflection to solve a given problem only when you have weighed it against other available mechanisms.
Code Download
For Further Reading
Page 3 of 3
This article was originally published on May 12, 2009