October 16, 2018
Hot Topics:

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

  • May 12, 2009
  • By 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");
    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.



    Enterprise Development Update

    Don't miss an article. Subscribe to our newsletter below.

    By submitting your information, you agree that developer.com may send you developer offers via email, phone and text message, as well as email offers about other products and services that developer believes may be of interest to you. developer will process your information in accordance with the Quinstreet Privacy Policy.


    Thanks for your registration, follow us on our social networks to keep up-to-date