JVM如何加载 .class文件?

Class.forName()方法
public static Class<?> forName(String className)
throws ClassNotFoundException {
Class<?> caller = Reflection.getCallerClass();
return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
}
谈谈反射
JAVA 反射机制是在运行状态中,对任意一个类,都能够知道这个类的所有属性和方法;对任意一个对象,都能够知道这个类的所有属性方法;对任意一个对象,都能够调用它的任意方法和属性;这种动态获取信息以及动态调用对象的方法功能称为java语言的反射机制。
写一个反射的例子
private String name;
public void sayHi(String helloSentence){
System.out.println(helloSentence+" " + name);
}
private String throwHello(String tag){
return "Hello" + tag;
}
}
public class ReflectSample {
public static void main(String[] args) throws Exception {
Class rc = Class.forName("com.huke.reflect.Robot");
Robot r = (Robot)rc.newInstance();
System.out.println("Class name is" + rc.getName());
Method getHello = rc.getDeclaredMethod("thowHello",String.class);
getHello.setAccessible(true);
Object str = getHello.invoke(r,"Bob");
System.out.println("getHello result is"+ str);
Method sayHi = rc.getMethod("sayHi",String.class);
sayHi.invoke(r,"Welcome");
Field name = rc.getDeclaredField("name");
name.setAccessible(true);
name.set(r,"Alice");
sayHi.invoke(r,"Welcome");
}
}
类从编译到执行的过程
1.编译器将Robot.java源文件编译为Robot.class字节码文件
2.ClassLoader将字节码转换为JVM中的Class对象
3.JVM利用Class对象实例化为Robot对象
2348

被折叠的 条评论
为什么被折叠?



