import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
class ReflectPoint {
private int x;
public int y;
public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}
}
public class Test {
public static void main(String[] args) throws Exception {
//Class类
String str1 = "abc";
Class cls1 = Class.forName("java.lang.String");
Class cls2 = String.class;
Class cls3 = str1.getClass();
System.out.println(cls1 == cls2); //true
System.out.println(cls2 == cls3); //true
System.out.println(int.class.isPrimitive()); //基本类型, true
System.out.println(int.class == Integer.TYPE); //Integer对应的基本类型字节码, true
System.out.println("---------");
//构造函数的反射
Constructor constructor1 = cls1.getDeclaredConstructor(String.class);
String str2 = (String) constructor1.newInstance(new String("ccc"));
System.out.println(str2);
System.out.println("---------");
//成员变量的反射
ReflectPoint pt1 = new ReflectPoint(3, 5);
Field fieldY = pt1.getClass().getField("y"); //getField要是共有的字段,fieldY是字节码
System.out.println(fieldY.get(pt1));
Field fieldX = pt1.getClass().getDeclaredField("x"); //getDeclaredField所有声明的都有
fieldX.setAccessible(true); //暴力反射
System.out.println(fieldX.get(pt1));
System.out.println("---------");
//函数方法的反射
String str3 = "xyz123";
Method methodCharAt = String.class.getMethod("charAt", int.class);
System.out.println(methodCharAt.invoke(str3, 1));
System.out.println("---------");
}
}
/*输出
true
true
*/