import java.lang.reflect.Constructor;
import java.lang.reflect.*;
import java.lang.reflect.Method;
public class reflact {
/**
* @param args
*/
public static void main(String[] args)throws Exception{
// TODO Auto-generated method stub
String x = "abc";
Class cls1 = x.getClass();
Class cls2 = String.class;
Class cls3 = Class.forName("java.lang.String");
System.out.println(cls1==cls3);
System.out.println(cls1==cls2);
System.out.println(cls1.isPrimitive());
Constructor cons = cls1.getConstructor(StringBuffer.class);
String str =(String) cons.newInstance(new StringBuffer("abc"));
System.out.println(str.charAt(2));
field fie = new field(3,5);
Field f = fie.getClass().getDeclaredField("x");
f.setAccessible(true);
System.out.println(f.get(fie));
changeab(fie);
System.out.println(fie);
Method method1 = String.class.getMethod("charAt", int.class);
System.out.println(method1.invoke(x,2));
}
private static void changeab(Object obj) throws Exception{
Field[] fies = field.class.getFields();
for (Field field : fies){
if (field.getType()== String.class){
String oldvalue= (String)field.get(obj);
String newvalue = oldvalue.replace('b', 'a');
field.set(obj,newvalue);
}
}
}
}
就这段代码 奇怪了。为什么上面的导包中只写import java.lang.reflect.*;不写import java.lang.reflect.Method;就会报错。按照道理来说
import java.lang.reflect.*;是包括import java.lang.reflect.Method;所以应该可以不写import java.lang.reflect.Method; 但是这里为什么不写不行?
|