本帖最后由 杨兴庭 于 2013-7-15 17:50 编辑
- import java.lang.reflect.Constructor;
- import java.lang.reflect.Field;
- import java.lang.reflect.Method;
- public class ReflectTest {
- public static void main(String[] args)throws Exception {
- String str = "abcde";
- Constructor constructor = String.class.getConstructor(StringBuffer.class);
- String str2 = (String)constructor.newInstance(new StringBuffer("abcdef"));
- System.out.println(str.charAt(3));
- ReflectPoint rp1 = new ReflectPoint(7,8);
- Field fieldy = rp1.getClass().getField("y");
- System.out.println(fieldy.get(rp1));
- Field fieldx = rp1.getClass().getDeclaredField("x");
- fieldx.setAccessible(true);
- System.out.println(fieldx.get(rp1));
- changeStringValue(rp1);
- System.out.println(rp1);
-
- Method methodCharAt = String.class.getMethod("charAt",int.class);
- System.out.println(methodCharAt.invoke(str, 1));
- System.out.println(methodCharAt.invoke(str, new Object[]{3}));
- String startClassName = args[0];
- //这里老是报错,可是明明是按照张孝祥老师的代码写的啊,而且怎么检查都没看出哪里错了
- Method mainMethod = Class.forName(startClassName).getMethod("main",String[].class);
- mainMethod.invoke(null,(Object)new String[]{"dsa","xzvdd","13124"});
- mainMethod.invoke(null,new Object[]{new String[]{"dsa","xzvdd","13124"}});
- }
- public static void changeStringValue(Object obj) throws Exception{
- Field[] fields = obj.getClass().getFields();
- for(Field field : fields){
- if(field.getType() == String.class){
- String oldvalue = (String)field.get(obj);
- String newvalue = oldvalue.replace('b', 'a');
- field.set(obj, newvalue);//这里是将新的字符串重新赋给obj吗?
- }
- }
- }
- }
- class TestArguments{
- public static void main(String[] args){
- for(String arg : args){
- System.out.println(arg);
- }
- }
- }
- public class ReflectPoint {
- public String str1 = "baeioahi";
- public String str2 = "bjoabjaboaiaobbbba";
- public String str3 = "rwqwrqwqw";
- @Override
- public String toString() {
- return "ReflectPoint [str1=" + str1 + ", str2=" + str2 + ", str3=" + str3 + "]";
- }
- }
复制代码 |