java反射 实例
package ref; public class Ref { private int age; private String name; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Ref(){ age=18; name="hans"; } public Ref(String s){ this.name=s; } public static void main(String[] args) { // TODO Auto-generated method stub Ref testReflect = new Ref(); final int m=10000; byte bytes[]; while(true){ bytes=new byte[500*m]; bytes=null; System.gc(); } } }
package ref; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; public class reftest { //获取类 public static void main(String[] args) throws ClassNotFoundException { Class c1=Class.forName("ref.Ref"); System.out.println(c1.getName()); System.out.println("////////////////////////"); // 实例化 try { Object o1=c1.newInstance(); } catch (InstantiationException | IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } //获取属性 Field[] f=c1.getDeclaredFields(); StringBuffer sb1=new StringBuffer(); sb1.append(Modifier.toString(c1.getModifiers()) + " class " + c1.getSimpleName() +"{\n"); for(Field f1:f){ sb1.append(Modifier.toString(f1.getModifiers())+" "); sb1.append(f1.getType().getSimpleName()+" "); sb1.append(f1.getName()+"\n"); } System.out.println(sb1+"}"); //获取方法 Method[] m=c1.getDeclaredMethods(); StringBuffer sb2=new StringBuffer(); sb2.append(Modifier.toString(c1.getModifiers()) + " class " + c1.getSimpleName() +"{\n"); for(Method m1:m){ sb2.append(Modifier.toString(m1.getModifiers())+" "); sb2.append(m1.getReturnType().getSimpleName()+" "); sb2.append(m1.getName()+"\n"); } System.out.println(sb2+"}"); // 获取构造方法 Constructor[] con=c1.getDeclaredConstructors(); StringBuffer sb3=new StringBuffer(); sb3.append(Modifier.toString(c1.getModifiers()) + " class " + c1.getSimpleName() +"{\n"); for(Constructor con1:con){ sb3.append(Modifier.toString(con1.getModifiers())+" "); //构造方法没有返回值 //sb3.append(con1.getReturnType().getSimpleName()+" "); sb3.append(con1.getName()+"\n"); } System.out.println(sb3+"}"); } }
结果如下:
ref.Ref //////////////////////// public class Ref{ private int age private String name } public class Ref{ public int getAge public void setAge public static void main public String getName public void setName } public class Ref{ public ref.Ref public ref.Ref }
不足之处
1,方法及构造方法里面的参数类型没有传回来;
2,构造方法前带着包名;