本帖最后由 王晓新 于 2012-6-17 09:32 编辑
- public class ReflectTest {
- public static void main(String[] args) throws Exception {
-
- Constructor<String> constructor = String.class.getConstructor(StringBuffer.class);
-
- String str = (String)constructor.newInstance(new StringBuffer("abc"));
-
- System.out.println(str.charAt(2));
-
- ReflectPoint pt = new ReflectPoint(2,5);
-
- Field fieldY = pt.getClass().getField("y");
-
- System.out.println(fieldY.get(pt));
-
- Field fieldX = pt.getClass().getDeclaredField("x");
-
- fieldX.setAccessible(true);//暴力访问
-
- System.out.println(fieldX.get(pt));
-
- changeStringValue(pt);
-
- System.out.println(pt);
-
- Method methodCharAt = String.class.getMethod("chatAt", int.class);//为嘛我运行的时候就说这句有问题呢?还有对这条语句的作用还是不大明白,哪位给解释一下
-
- System.out.println(methodCharAt.invoke(str, 1));
- }
- private 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);
- }
- }
-
-
- }
- }
复制代码 |
|