根据
http://www.iteye.com/topic/137944
文档进行学习
代码如下:
package reflectTest; import java.lang.reflect.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; class A{ } class B extends A{ } class C extends B{ } class TestClass extends Object implements ActionListener { private int a = 3; public Integer b = 4; public TestClass(){} public TestClass(int id,String name){} public void Abc(int id,String name){} public void ActionPerformed(ActionEvent e){} } public class Main { public static void main(String[] args) { // TODO Auto-generated method stub TestClass tc = new TestClass(); Class temp = tc.getClass(); //============================================== try{ System.out.println("反射类中所有公有的属性"); Field[] fb = temp.getFields(); for(int i=0;i < fb.length;i++) { Class cl = fb[i].getType(); System.out.println("fb: "+cl); } System.out.println("反射类中所有的属性"); Field[] fa = temp.getDeclaredFields(); for(int i = 0;i < fa.length;i++) { Class cl = fa[i].getType(); System.out.println("fa: "+cl); } System.out.println("反射类中私有属性的值"); Field f = temp.getDeclaredField("a"); f.setAccessible(true); Integer i = (Integer)f.get(tc); System.out.println(i); //=============================== String className = temp.getName(); Constructor[] constructs = temp.getConstructors(); for(int k = 0;k < constructs.length;k++) { Class[] Parametertypes = constructs[k].getParameterTypes(); System.out.print(className + "("); for(int j =0 ;j < Parametertypes.length;j++) { System.out.print(Parametertypes[j].getName()+" "); } System.out.println(")"); } //================================================================== Class[] interfaces = temp.getInterfaces(); for(int j = 0;j<interfaces.length;j++) { System.out.println(interfaces[j].getName()); } Class superClass = temp.getSuperclass(); System.out.println(superClass.getName()); //================================================================= C c = new C(); Class t = c.getClass(); Class superClass1 = t.getSuperclass(); System.out.println(c); System.out.println(c.getClass()); System.out.println(c.getClass().getSuperclass()); System.out.println(c.getClass().getSuperclass().getSuperclass()); }catch(Exception e) { System.out.println(e); } } }
运行结果如下:
反射类中所有公有的属性
fb: class java.lang.Integer
反射类中所有的属性
fa: int
fa: class java.lang.Integer
反射类中私有属性的值
3
reflectTest.TestClass()
reflectTest.TestClass(int java.lang.String )
java.awt.event.ActionListener
java.lang.Object
reflectTest.C@70dea4e
class reflectTest.C
class reflectTest.B
class reflectTest.A