{
String oldValue = (String)field.get(obj);
String newValue = oldValue.replace('b', 'a');
field.set(obj, newValue);
}
}
}
}
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.class) // 为什么不用getClass()
{
String oldValue = (String)field.get(obj);
String newValue = oldValue.replace('b', 'a');
field.set(obj, newValue);
}
}
}
}下面是例子中用到的ReflectPoint类: [java]
public class ReflectPoint {
private int x;
public int y;
public String str1 = "ball";
public String str2 = "basketball";
public String str3 = "itcast";
public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "ReflectPoint [x=" + x + ", y=" + y + ", str1=" + str1
+ ", str2=" + str2 + ", str3=" + str3 + "]";
}
}
public class ReflectPoint {
private int x;
public int y;
public String str1 = "ball";
public String str2 = "basketball";
public String str3 = "itcast";
public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "ReflectPoint [x=" + x + ", y=" + y + ", str1=" + str1
+ ", str2=" + str2 + ", str3=" + str3 + "]";
}
}
12. Method类, 成员方法的反射:
调用方法的invoke(obj, args)执行, 如果第一个参数为null, 就说明是调用的静态方法.
[java]
import java.lang.reflect.Method;
public class Test3 {
public static void main(String[] args) throws Exception{
String str = "asdf";
Method methodCharAt = String.class.getMethod("charAt", int.class);
char c = (char)methodCharAt.invoke(str, 2);
System.out.println(c);
}
}
import java.lang.reflect.Method;
public class Test3 {
public static void main(String[] args) throws Exception{
String str = "asdf";
Method methodCharAt = String.class.getMethod("charAt", int.class);
char c = (char)methodCharAt.invoke(str, 2);
System.out.println(c);
}
}
13. 对接收数组参数的成员方法的反射(调用main方法示例): 为了兼容jdk1.4, 如果直接传入一个数组, 则会把这个数组打散, 使其与传入多个元素相同. [java]
import java.lang.reflect.Method;
class TestArguments{
public static void main(String[] args) {
for(String arg: args){
System.out.println(arg);
}
}
}
public class Test3 {
public static void main(String[] args) throws Exception{
String startingClassName = args[0];
Method mainMethod = Class.forName(startingClassName).getMethod("main", String[].class);
mainMethod.invoke(null, new Object[]{new String[]{"111","222","333"}}); //* 为了兼容JDK1.4, 会把传入的数组打散开. 这里就作为三个元素. 把数组强制转换成(Object)也行.
}
}
import java.lang.reflect.Method;
class TestArguments{
public s