JVM-类的四种载入方式

时间:2022-03-11 20:55:48
package org.burning.sport.javase.classloader;


public class ClassLoaderMain {
    public static void main(String[] args) {

        ClassLoaderMain clm = new ClassLoaderMain();
        //1.使用Class静态方法Class.forName
//        clm.loadClassMethod1();

        //2.使用ClassLoader
//        clm.loadClassMethod2();

        //3. 使用类.class方式
//        clm.loadClassMethod3();

        //4. 使用对象的getClass方法
        clm.loadClassMethod4();
    }

    public void loadClassMethod1() {
        try {
            Class<?> clazz = Class.forName("org.burning.sport.javase.classloader.ClassLoaderModel"); ClassLoaderModel clm = (ClassLoaderModel)clazz.newInstance();
            System.out.println(clm);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void loadClassMethod2() {
        ClassLoader cl = this.getClass().getClassLoader(); try {
            Class<?> clazz = cl.loadClass("org.burning.sport.javase.classloader.ClassLoaderModel");
            ClassLoaderModel clm = (ClassLoaderModel) clazz.newInstance();
            System.out.println(clm);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void loadClassMethod3() {
        Class<?> clazz = ClassLoaderModel.class;
        try {
            ClassLoaderModel str = (ClassLoaderModel)clazz.newInstance();
            System.out.println(str);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public void loadClassMethod4() {
        ClassLoaderModel clm = new ClassLoaderModel();
        Class<?> clazz = clm.getClass();
        try {
            ClassLoaderModel ss = (ClassLoaderModel)clazz.newInstance();
            System.out.println(ss);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

 https://gitee.com/play-happy/base-project

Class.forName()和ClassLoader.loadClass()区别

  •   Class.forName():将类的.class文件加载到jvm中之外,还会对类进行解释,执行类中的static块;
  •   ClassLoader.loadClass():只干一件事情,就是将.class文件加载到jvm中,不会执行static中的内容,只有在newInstance才会去执行static块。
  •   Class.forName(name,initialize,loader)带参函数也可控制是否加载static块。并且只有调用了newInstance()方法采用调用构造函数,创建类的对象 。

 参考:

  【1】博客,http://www.cnblogs.com/ityouknow/p/5603287.html