Java底层:JVM(二)

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对象

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值