dcsimg
April 5, 2020
Hot Topics:

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

  • By Sridhar M S
  • Send Email »
  • More Articles »

Using Reflection to Retrieve Attributes

A class has other entities besides the ones you have seen so far. What about variables, for example? You can use reflection to get a detailed output of these entities as well. Here is another example using a Field class:
import java.lang.reflect.*;
 
public class DumpFields {
  public static void main(String args[])
  {
     try {
         Class c = Class.forName(args[0]);
         Field[] fields = c.getFields();
         for (int i = 0; i < fields.length; i++)
         System.out.println(fields[i].toString());
     }
     catch (Throwable e) {
        System.err.println(e);
     }
  }
}
When you compile this and execute it with an argument of Employee...
java DumpFields Employee 
...You receive the following output:
public java.lang.String Employee.empNum
public java.lang.String Employee.empName
This result lists all the fields/attributes that belong to the class.

Using Reflection to Retrieve Constructors

This example of a Constructor class will help complete your understanding of the various constructors available, as well as how to use them.
import java.lang.reflect.*;
 
public class DumpConstructors {
  public static void main(String args[])
  {
     try {
         Class c = Class.forName(args[0]);
         Constructor[] constructor = c.getConstructors();
         for (int i = 0; i < constructor.length; i++)
         {
             System.out.println(constructor[i].toString());
            //To print the parameter types
            Class pvec[] = constructor[i].getParameterTypes();
            for (int j = 0; j < pvec.length; j++)
                System.out.println("param #" + j + " " 
+ pvec[j]); } } catch (Throwable e) { System.err.println(e); } } }
When you compile this and execute it with an argument of Employee...
javac DumpConstructors Employee
...You receive the following result:
public Employee(java.lang.String,java.lang.String)
param #0 class java.lang.String
param #1 class java.lang.String
public Employee()
Analyzing the result, you will find that the Employee class has two constructors. The first one is a parameterized constructor (you can see the parameter types also). The second does not take any parameters and the result is self-explanatory.





Page 2 of 3



This article was originally published on May 12, 2009

Enterprise Development Update

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


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