ReflectionDemo.java

Download ReflectionDemo.java

 1: // Demo of simple reflection.
 2: // Note that all objects automatically have a "toString" method,
 3: // and using "System.out.println( ... + obj + ... );" will use it.
 4: //
 5: // Written 10/2010 by Wayne Pollock, Tampa Florida USA.
 6: 
 7: import java.lang.reflect.Method;
 8: import java.util.Date;
 9: import java.util.Scanner;
10: 
11: public class ReflectionDemo
12: {
13:    public static void main ( String [] args ) throws Exception
14:    {
15:       Scanner in = new Scanner ( System.in );
16: 
17:       System.out.print( "Enter a class name (e.g., java.util.Date): " );
18:       String name = in.next();
19: 
20:       Class cl = Class.forName( name );  // Load some class into the JVM.
21: 
22:       System.out.println( name + ".class: " + cl.getName() );
23: 
24:       Object obj = cl.newInstance();  // Uses no-arg constructor.
25:       System.out.println( "obj.toString(): " + obj );
26: 
27:       System.out.println( "Enter one of the following \"no-arg\" method "
28:         + "names for " + cl + ":\n" );
29: 
30:       Method[] methods = cl.getMethods();
31:       for ( Method m : methods )
32:       {
33:          if ( m.getParameterTypes().length == 0 )
34:             System.out.println( "\t" + m );  // Print methods that take no args
35:       }
36: 
37:       System.out.print( "\nEnter method name (e.g., \"toString\"): " );
38:       String methodName = in.next();
39: 
40:       @SuppressWarnings("unchecked") // Turn off warning about unchecked types.
41:       Method method = cl.getMethod( methodName );
42:       Object result = method.invoke( obj );
43:       System.out.println( "method " + cl.getName() + "." + method.getName()
44:          + " returned: " + result );
45: 
46: //    ---------------------------------------------------------------
47: 
48:       // Shows use of "class" final field (same as obj.getClass()):
49:       cl = Date.class;
50:       System.out.println( "\n\nDate.class: " + cl.getName() );
51: 
52:       /* Shows internal mangled names for "internal" types, such as
53:        * primitives and arrays.  Here's a list of these:
54:        *    B (byte)
55:        *    C (char)
56:        *    D (double)
57:        *    F (float)
58:        *    I (int)
59:        *    J (long)
60:        *    S (short)
61:        *    Z (boolean)
62:        *    Lclassname;  (object types)
63:        *    [type (array of type)
64:        */
65: 
66:       obj = new Double[10];  // Array of Double objects
67:       cl = obj.getClass();
68:       System.out.println( "Array of Double: " + cl.getName() );
69: 
70:       obj = new double[10];  // array of double primitives
71:       cl = obj.getClass();
72:       System.out.println( "Array of double: " + cl.getName() );
73:    }
74: }