April 24, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

What's Going On in There? Java Reflection for Program Insight, Page 3

  • May 12, 2009
  • By Sridhar M S, Sridhar M S
  • Send Email »
  • More Articles »

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", 
new Class[]{new Properties().getClass()}); } catch (Exception ex) { //Exception in loading Class:" + ex.getMessage(); }
These utilities allow an IDE developer to accommodate Java as a supported programming language quite easily.

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

  • Reflection_src

    For Further Reading

  • "Using Java Reflection" (from Sun Developer Network)
  • "Trail: The Reflection API" (from Sun Developer Network)




  • Page 3 of 3



    Comment and Contribute

     


    (Maximum characters: 1200). You have characters left.

     

     


    Sitemap | Contact Us

    Rocket Fuel