20-CS-694 Advanced Programming Techniques Spring 2012
Reflection

Interfaces, Exceptions, Graphics, Animation, Threads, Reflection, Networking, RMI, JDBC, JNI

All lectures
Basics

This series shows how to use many of the classes associated with reflection. Click on the class names in the following table to see class details.

Class Method Constructor Field Modifier Array

1.   DumpMethods.java

  -   List all methods of a class. The important lines are:
   Class c = Class.forName(text.getText());
   Method m[] = c.getDeclaredMethods();
 
2.   instance1.java

  -   Test Whether Given Object is of Particular Class Type. Important lines are:
   Class cls = Class.forName("Z");
   boolean b1 = cls.isInstance(new Integer(37));
 
3.   constructor1.java

  -   List all constructor attributes of a class. Important lines are:
   Class cls = Class.forName("A");
   Constructor ctorlist[] = cls.getDeclaredConstructors();
   Constructor ct = ctorlist[i];
   ... ct.getName() ...
   ... ct.getDeclaringClass() ...
   Class pvec[] = ct.getParameterTypes();
   Class evec[] = ct.getExceptionTypes();
 
4.   constructor2.java

  -   Create a class instance using a constructor specification.

 
5.   method1.java

  -   List method specifications of a given class. Important lines are:
   Class cls = Class.forName(text.getText());
   Method methlist[] = cls.getDeclaredMethods();
   Method m = methlist[i];
   ... m.getName() ...
   ... m.getDeclaringClass() ...
   Class pvec[] = m.getParameterTypes();
   Class evec[] = m.getExceptionTypes();
 
6.   method2.java

  -   Invoke a method. Important lines are the following:
   Class  cls = Class.forName("C");
   Method m = cls.getMethod("add", new Class[] { Integer.TYPE, ... });
   Constructor ct = cls.getConstructor();
   C m_obj = (C)ct.newInstance();
   Object retobj = m.invoke(m_obj, new Object[] { new Integer(37), ... });
 
7.   field1.java

  -   List the fields of a class. Important lines are:
   Class cls = Class.forName("D");
   Field fieldlist[] = cls.getDeclaredFields();
   Field fld = fieldlist[i];
   ... fld.getName() ...
   ... fld.getDeclaringClass() ...
   ... fld.getType() ...
   ... fld.getModifiers() ...
 
8.   field2.java

  -   Examine and set field values. Important lines are:
   Class  cls = Class.forName("E");
   Field fld = cls.getField("d");
   Constructor ct = cls.getConstructor( );                        
   E obj = (E)ct.newInstance( );
   ... fld.getDouble(obj) ...
   ... fld.setDouble(obj, 12.34) ...
 
9.   array1.java

  -   Set array values. Important lines are:
   Class cls = Class.forName("java.lang.String");
   Object arr = Array.newInstance(cls, 10);
   Array.set(arr, 5, "this is a test");
   ... Array.get(arr, i) ...