//是接收StringBuffer的构造方法, 所以要传入StringBuffer对象
String str = (String)constructor1.newInstance(new StringBuffer("abc"));
System.out.println(str);
System.out.println(str.charAt(2));
}
}
import java.lang.reflect.Constructor;
class Test2
{
public static void main(String [] args) throws Exception
{
//反射获得接收StringBuffer的构造方法
Constructor constructor1 = String.class.getConstructor(StringBuffer.class);
//是接收StringBuffer的构造方法, 所以要传入StringBuffer对象
String str = (String)constructor1.newInstance(new StringBuffer("abc"));
System.out.println(str);
System.out.println(str.charAt(2));
}
}
10. Field类, 成员变量的反射应用:
[java]
import java.lang.reflect.Field;
class Test2
{
public static void main(String [] args) throws Exception
{
ReflectPoint pt1 = new ReflectPoint(3, 5);
Field fieldY = pt1.getClass().getField("y"); //getField()方法只能获取可见的
Field fieldX = pt1.getClass().getDeclaredField("x"); //getDeclaredField()方法连不可见的也能获取(此处x是private修饰的)
//fieldY不是对象身上的变量, 而是类, 若果要取值需要指定取哪个对象的
System.out.println(fieldY.get(pt1));
//由于Reflect的x变量是私有的, 不可见, 所以这里要先setAccessible(true), 之后才能访问. * 这叫暴力反射!
fieldX.setAccessible(true);
System.out.println(fieldX.get(pt1));
}
}
import java.lang.reflect.Field;
class Test2
{
public static void main(String [] args) throws Exception
{
ReflectPoint pt1 = new ReflectPoint(3, 5);
Field fieldY = pt1.getClass().getField("y"); //getField()方法只能获取可见的
Field fieldX = pt1.getClass().getDeclaredField("x"); //getDeclaredField()方法连不可见的也能获取(此处x是private修饰的)
//fieldY不是对象身上的变量, 而是类, 若果要取值需要指定取哪个对象的
System.out.println(fieldY.get(pt1));
//由于Reflect的x变量是私有的, 不可见, 所以这里要先setAccessible(true), 之后才能访问. * 这叫暴力反射!
fieldX.setAccessible(true);
System.out.println(fieldX.get(pt1));
}
}下面是例子中用到的ReflectPoint类: [java]
public class ReflectPoint {
private int x;
public int y;
public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}
}
public class ReflectPoint {
private int x;
public int y;
public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}
}
11.* 成员变量反射的综合案例:
[java]
import java.lang.reflect.Field;
class Test2
{
public static void main(String [] args) throws Exception
{
ReflectPoint pt1 = new ReflectPoint(3, 5);
System.out.println(pt1);
changeStringValue(pt1);
System.out.println(pt1);
}
private static void changeStringValue(Object obj) throws Exception {
Field[] fields = obj.getClass().getFields();
for(Field field: fields){
if(field.getType() == String.cla