package enhance_day1;
import java.lang.reflect.*;
import java.text.DateFormat.Field;
public class ReflectTest1 {
public static void main(String[] args) throws Exception, IllegalAccessException, ClassNotFoundException
{
Constructor constructor= String.class.getConstructor(StringBuffer.class);
String str2=(String)constructor.newInstance(new StringBuffer("abccd"));
System.out.println(str2.charAt(2));
ReflectPoint pt1=new ReflectPoint(3,5);
java.lang.reflect.Field fieldY=pt1.getClass().getField("y");
System.out.println(((java.lang.reflect.Field) fieldY).get(pt1));
java.lang.reflect.Field fieldX=pt1.getClass().getDeclaredField("x");
System.out.println(((java.lang.reflect.Field) fieldX).get(pt1));
changeStringValue(pt1);
System.out.println(pt1);
}
public static void changeStringValue(Object obj) throws Exception
{
java.lang.reflect.Field[] fields=obj.getClass().getFields();
for(java.lang.reflect.Field field:fields)
{
if(field.getType()==String.class);
String oldValue=(String)field.get(obj);
String newValue=oldValue.replace('b','a');
field.set(obj,newValue);
}
}
}
运行时提示
|