Java内省和反射机制三步曲之(2)反射
public static void main(String[] args) throws Exception { Constructor constructor = String.class.getConstructor(StringBuffer.class); String str2 =(String)constructor.newInstance(new StringBuffer("abc")); //newInstance()返回的是一个Object,所以要用类型转换 System.out.println(str2); String str3 = (String)constructor.newInstance("abc"); System.out.println(str3);//有异常:argument type mismatch //获得构造方法时要调用的参数类型和调用获得方法时要有相同的参数类型 }
?
public class Point { public Integer x; private Integer y; public Point(Integer x, Integer y) { super(); this.x = x; this.y = y; } } public static void main(String[] args) throws Exception { Point reflect = new Point(2, 5); Field fieldX = Point.class.getField("x"); // 此时fieldX的值不是5,fieldX不是对象身上的变量,而是类上,要用它去取对象身上的值,必须和实例对象结合使用。 Integer valueX = (Integer) fieldX.get(reflect); System.out.println(valueX);// 2 // Field fieldY = Point.class.getField("y"); // // 由于属性y的修饰符是private,所以程序运行到此处就有异常,说该属性不存在:java.lang.NoSuchFieldException: y // Integer valueY = (Integer) fieldY.get(reflect); // // 下面的方法可以解决无法查看私有属性的方法 // Field fieldY2 = Point.class.getDeclaredField("y"); // //getDeclaredField():只要声明的变量都可以查看,运行到此处无异常 // Integer valueY2 = (Integer) fieldY2.get(reflect); // // 在这里会有异常,属性虽然存在,但无法访问:Class com.sun.Reflect can not access a member of class com.sun.Point with modifiers "private" // 暴力反射,即使设为private的属性变量依然可以访问, Field fieldY3 = Point.class.getDeclaredField("y"); fieldY3.setAccessible(true); Integer valueY3 = (Integer) fieldY3.get(reflect); System.out.println(valueY3);// 5 //一个代表看不见,一个代表看见了但取出到值,就类如:(一)我看不到别人的钱,(二)是我看到了,但是用不到,暴力反射就相当于"qiangjie". } 相关代码二: public class Point { public String str1 = "who"; public String str2 = "when"; public String str3 = "where"; public Integer num = 5; public boolean istrue = true; public String toString() { return str1 + "-" + str2 + "-" + str3 + "-" + num + "-" + istrue; } } public class Reflect { public static void main(String[] args) throws Exception { Point point = new Point(); System.out.println(point);// who-when-where-5-true changeFieldValues(point); System.out.println(point);// Who-When-Where-5-true:把"w"改成了大写的"W" //我们看到了反射可以任意改变属性的值,这种应用在很多框架中都有使用! } private static void changeFieldValues(Point point) throws IllegalAccessException { Field[] fields = Point.class.getFields(); for (Field field : fields) { if (field.getType() == String.class) { String oldVal = (String) field.get(point); String newVal = oldVal.replace("w", "W"); field.set(point, newVal); } } } } ?public static void main(String[] args) throws Exception { String str = "welcome!"; Method charAt = String.class.getMethod("charAt", int.class); System.out.println(charAt.invoke(str, 0));// w } ??