本帖最后由 李志群 于 2012-11-28 16:48 编辑
package cn.itcast.day1;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectTest {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
String str = "abc";
Class clas1 = str.getClass();
Class clas2 = String.class;
Class clas3 = Class.forName("java.lang.String");
System.out.println(clas1==clas2);
System.out.println(clas1==clas3);
System.out.println(clas1.isPrimitive());
System.out.println(int.class.isPrimitive());
System.out.println(int.class==Integer.class);
System.out.println(int.class==Integer.TYPE);
System.out.println(int[].class.isPrimitive());
System.out.println(int[].class.isArray());
//new String(new StringBuffer("abs"));
Constructor constructor = String.class.getConstructor(StringBuffer.class);
String str2 =(String)constructor.newInstance(new StringBuffer("abc"));
System.out.println(str2.charAt(2));
ReflectPoint pt1 = new ReflectPoint (3,5);
Field filed = pt1.getClass().getField("y");
//filed Y的值是多少?是5就是错的。filed Y 不是对象身上的变量,而是类上的,要用它去取某个对象上对应的值
System.out.println(filed.get(pt1));
Field filed1 = pt1.getClass().getDeclaredField("x");
filed1.setAccessible(true);
System.out.println(filed1.get(pt1));
changeStringValue(pt1);
System.out.println(pt1);
Method methodCharAt = String.class.getMethod(str,int.class);
System.out.println(methodCharAt.invoke(str, 1));
System.out.println(methodCharAt.invoke(str,new Object[]{2}));
// Method methodCharAt = String.class.getMethod("CharAt",int.class);
//
//
// System.out.println(methodCharAt.invoke(str,1));//这句输出怎么就出异常了 0 0!!!
}
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);
}
}
}
}
打印的结果是:
true
true
false
true
false
true
false
true
c
5
3
ReflectPoint [str1=aall, str2=aasketaall, str3=itcast]
Exception in thread "main" java.lang.NoSuchMethodException: java.lang.String.abc(int)
at java.lang.Class.getMethod(Class.java:1622)
at cn.itcast.day1.ReflectTest.main(ReflectTest.java:48)
怎么会报异常呢?我照着打的 思路也对啊
|