next up previous contents
Next: Introspection Up: Examples Previous: Examples   Contents

Simple Example

Attempt to show the main functionality of the Reflection API:
import java.lang.reflect.*;  
public class Pt {                                                     
    public int x = 0;                                                 
    public Pt max(Pt other) {                                         
      System.out.println("max");                                     
      return x > other.x ? this : other;                              
    }                                                                 
    public static void main(String args[])                            
    {	try {                                                           
	    // get the class                                            
	    Class pclass = Class.forName("Pt");                         
	                                                                
	    // alternatively:   Class pclass = (new Pt()).getClass();  

	    // create an instance                                       
	    Pt p = (Pt) pclass.newInstance();                           
                                                                      
	    // reflect on a field                                       
	    Field fx = pclass.getField("x");                            
	    fx.setInt(p, 10);                                           
	    System.out.println("x value: "+ fx.getInt(p));              
	                                                                
	    // call a method                                            
	    //   (2nd argument is array of Class'es for parameters      
	    Class marg_types[] = new Class[1];                          
	    Object margs[] = new Object[1];                             
                                                                      
	    marg_types[0] = p.getClass();                              
	    Method m = pclass.getMethod("max", marg_types);             
                                                                      
	    margs[0] = p;     // the argument                           
	    Pt res = (Pt) m.invoke(p, margs);                           
	} catch (Exception e) { e.printStackTrace(); }                  
    }                                                                 
}                                                                     

Output:
_______________
| x value: 10 |
| max         |
|_____________|



Nadeem Hamid 2000-07-24