package javaenhance.com.itheima;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
public class ConstructorDemo {
/**
* @param args
*/
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
String str1="abc";
Class cls1=str1.getClass();
Class cls2=String.class;
Class cls3=Class.forName("java.lang.String");
System.out.println(cls1==cls2);
System.out.println(cls1==cls3);
System.out.println(cls1.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("abc"));
Constructor constructor1=String.class.getConstructor(StringBuffer.class);
String str2=(String)constructor1.newInstance(new StringBuffer("abc"));
System.out.println(str2.charAt(2));
ReflectPoit pt1=new ReflectPoit(3,5);
Field fieldY=pt1.getClass().getField("y");//fieldY不是对象身上的变量,而是类上,要用它去取某个对象上对应的值
System.out.println((fieldY.get(pt1)));
Field fieldX=pt1.getClass().getDeclaredField("x");
fieldX.isAccessible();
System.out.println(fieldX.get(pt1));
changeStringValue(pt1);//-------------------------->这行出错!!!!!!!!!!!!!
System.out.println(pt1);
}
private static void changeStringValue(Object obj)throws Exception {
// TODO Auto-generated method stub
//对字节码用==比 !专业!
Field[] fields=obj.getClass().getFields();
for(Field field:fields){
if(field.getType()==String.class){
String oldString=(String)field.get(obj);
String newString=oldString.replace('b', 'a');
field.set(obj, newString); //将obj对象中的field变量值改成newString
}
}
}
}
老师视频里面 运行是对的! 错误原因是 Object 类型无法接受ReflectPoit 类型!Object 是上帝啊 怎么可能无法接受???jre 1.6版本!
package javaenhance.com.itheima;
/**
* @author Administrator
*
*/
public class ReflectPoit {
public int x;
public int y;
public String str1="ball";
public String str2="basketball";
public String str3="itcast";
public ReflectPoit(int x, int y) {
super();
this.x = x;
this.y = y;
}
@Override
public String toString()
{
return str1+":"+str2+":"+str3;
}
}
|
|