作用
反射机制可以读和修改字节码文件
如何获取类的字节码
public class Test06 {
public static void main(String[] args) {
//第一种方式
Class c=null;
try {
c=Class.forName("Bird");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
Object o=c.newInstance();
System.out.println(o);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
//第二种方式
Bird bird=new Bird();
Class cc=bird.getClass();
try {
Object o=cc.newInstance();
System.out.println(o);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
//第三种方式
String s="hello word";
Class a=s.getClass();
Class ccc=String.class;
try {
Object o=ccc.newInstance();
System.out.println(a==ccc);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
class Bird{
public Bird() {
System.out.println("无参数构造方法");
}
}