恩谢谢,
看看这段代码错那了:
package first;
import java.lang.reflect.*;
public class TestDemo {
/**
* @param args
*/
public static void main(String[] args)throws Exception{
//TODO Auto-generated method stub
String str="afa";
Class cls1=str.getClass();
Class cls2=String.class;
Class cls3=Class.forName("java.lang.String");
System.out.println(cls1 ==cls2);//true
System.out.println(cls1 ==cls3);//true
System.out.println(cls1.isPrimitive());//false
System.out.println(int.class.isPrimitive());//isprimitive()判断该字节码是否为基本类型的字节码true
System.out.println(int.class == Integer.class);//false
System.out.println(int.class == Integer.TYPE);//true
// 用反射实现该语句newString(new StringBuffer("afa"));
Constructor constructor=String.class.getConstructor(StringBuffer.class);
String str1=(String)constructor.newInstance(new StringBuffer("afhf"));//构造器实例化返回String类
System.out.println(str1.charAt(2));
//成员变量的反射
ReflectPoint pt1=new ReflectPoint(3,5);
Field fieldY=pt1.getClass().getField("y");
System.out.println(fieldY.get(pt1));
Field fieldX=pt1.getClass().getDeclaredField("x");//获取已声明的字段,存在的就行
fieldX.setAccessible(true);//设置该字段的可访问权限
System.out.println(fieldX.get(pt1));
}
} |