1 import java.lang.reflect.*; 2 3 class reflectDemo 4 { 5 public static void main(String[] args) throws Exception 6 { 7 String s="Hello World"; 8 //创建Class对象的三种方式。 9 Class c1=String.class; 10 Class c2=s.getClass(); 11 Class c3=Class.forName("java.lang.String");//使用较多 12 System.out.println("String.class==s.getClass():"+(c1==c2)); 13 System.out.println("String.class==Class.forName:"+(c1==c3)); 14 15 System.out.println(Integer.TYPE==int.class); 16 Constructor con=String.class.getConstructor(StringBuffer.class); 17 18 String s2=(String)con.newInstance(new StringBuffer("dfdf")); 19 System.out.println(s2); 20 System.out.println("____________"); 21 22 ReflectPoint pt1=new ReflectPoint(4,8); 23 Field fieldy=pt1.getClass().getField("y");//这个方法只可获取到公共的成员变量 24 System.out.println(fieldy.get(pt1)); 25 26 27 Field fieldx=pt1.getClass().getDeclaredField("x");//该方法可以获取到私有的成员变量,但是无法获取 28 fieldx.setAccessible(true);//必须使用暴力访问,才可以访问private修饰的成员变量 29 System.out.println(fieldx.get(pt1)); 30 31 //将Sting的成员变量中的b都换为a. 32 changeStringValue(pt1); 33 System.out.println(pt1); 34 35 System.out.println("____________"); 36 //使用反射得到方法,调用str1.char(1) 37 Method methodCharAt=String.class.getMethod("charAt",int.class); 38 System.out.println(methodCharAt.invoke(s,1)); 39 40 // 41 if(args.length==1){ 42 String startingClassName=args[0]; 43 Method mainMethod=Class.forName("startingClassName").getMethod("main",String[].class); 44 //mainMethod.invoke(null, new Object[]{new String[]{"12","131"}}); 45 mainMethod.invoke(null, (Object)new String[]{"12","131"}); 46 47 } 48 int[] it1=new int[3]; 49 int[] it2=new int[4]; 50 String[] str1=new String[4]; 51 String[][] str2=new String[3][2]; 52 System.out.println(it1.getClass()==it2.getClass()); 53 //System.out.println(str1.getClass()==str2.getClass()); 54 System.out.println(str2.getClass().getName()); 55 System.out.println(it1.getClass().getName()); 56 System.out.println(it1.getClass().getSuperclass().getName()); 57 58 } 59 private static void changeStringValue(Object obj)throws Exception{ 60 Field[] fields=obj.getClass().getFields(); 61 for(Field field:fields){ 62 //if(field.getType().equals(String.class)) 63 if(field.getType()==String.class){ 64 String oldValue=(String)field.get(obj); 65 String newValue=oldValue.replace('b','a'); 66 field.set(obj,newValue); 67 } 68 } 69 70 } 71 } 72 class ReflectPoint 73 { 74 private int x; 75 public int y; 76 public String st1="ball"; 77 public String st2="basketball"; 78 public String st3="itcast"; 79 ReflectPoint(int x,int y){ 80 this.x=x; 81 this.y=y; 82 } 83 public String toString(){ 84 return st1+" "+st2+" "+st3; 85 } 86 } 87 class TestArguments 88 { 89 public static void main(String[] args){ 90 for(String sr:args){ 91 System.out.println("调用主函数:"+sr); 92 } 93 } 94 }