美文网首页
类加载的两种方式:forName()和loadClass()详解

类加载的两种方式:forName()和loadClass()详解

作者: 啊啊啊哼哼哼 | 来源:发表于2020-05-19 11:20 被阅读0次

forName()

  • forName() 是Class类的方法
  • Returns the {@code Class} object associated with the class or interface with the given string name.
 public static Class<?> forName(String name, boolean initialize, ClassLoader loader) throws ClassNotFoundException
  • 用forName()实现反射
package jvm.reflect;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class reflectTest {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, NoSuchFieldException, InvocationTargetException {
        Class r = Class.forName("jvm.reflect.Shop");
        //能访问私有的方法,但是不能访问继承或者实现接口的方法
        Method getName = r.getDeclaredMethod("getName", String.class);
        //因为getName是私有方法,所以要把方法设置为true
        getName.setAccessible(true);

        //不能访问私有的方法,但是可以访问继承或者实现接口的方法
        Method outName = r.getMethod("outName");

        //通过newInstance创建一个对象,但是不能传递参数
        Shop s = (Shop) r.newInstance();

        //获得属性name
        Field name = r.getDeclaredField("name");
        //将私有属性设置为可访问
        name.setAccessible(true);
        //传递参数,设置name属性值
        name.set(s, "qinxiaoyu");

        //获得属性name
        Field id = r.getDeclaredField("id");
        //将私有属性设置为可访问
        id.setAccessible(true);
        //传递参数,设置name属性值
        id.set(s, 419);

        System.out.println(getName.invoke(s, "hello"));
        outName.invoke(s);
    }
}

loadClass()

  • ClassLoader是一个抽象类,一个class loader对象负责加载类,通常的策略是将类名转换为文件名,从文件系统中读取一个类文件;
A class loader is an object that is responsible for loading classes. The class <tt>ClassLoader</tt> is an abstract class.  Given the <a href="#name">binary name</a> of a class, a class loader should attempt to locate or generate data that constitutes a definition for the class.  A typical strategy is to transform the name into a file name and then read a "class file" of that name from a file system.

自定义一个类加载器,继承ClassLoader,重写ClassLoader的findClass方法

  • 如何自定义类加载器,我们可以从源码注释里找到例子,下面是Java源码给出的实现ClassLoader的一个简单的例子;
  • findClass包括loadClassData和defineClass两部分,loadClass方法加载类文件为二进制数据,然后通过define方法加载类的二进制数据,返回一个Class对象。
        public Class findClass(String name) {
              byte[] b = loadClassData(name);
              return defineClass(name, b, 0, b.length);
         }
 
          private byte[] loadClassData(String name) {
              // load the class data from the connection
              &nbsp;.&nbsp;.&nbsp;.
          }
  • 下面给出一个自定义ClassLoader的例子
package jvm.reflect;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class MyClassLoader extends ClassLoader {
    //文件路径
    private String path;

    MyClassLoader(String path) {
        this.path = path;
    }

    //加载文件数据,然后通过defineClass将二进制文件数据转换为类的对象
    @Override
    public Class findClass(String name) throws ClassNotFoundException {
        byte[] b = new byte[0];
        try {
            b = loadClassData(name);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return defineClass(name, b, 0, b.length);
    }

    //按照文件名,加载文件,返回二进制数组
    private byte[] loadClassData(String name) throws IOException {
        name = path + name + ".class";
        FileInputStream in = new FileInputStream(new File(name));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int i;
        while ((i = in.read()) != -1) {
            out.write(i);
        }
        out.close();
        in.close();
        return out.toByteArray();
    }
}

类的隐式加载和显示加载

  • 隐式加载类的方法new;显示加载类的方法forName()和loadClass()
  • 隐式加载直接创建一个对象,并且可以调用类的构造器方法传递参数
  • 显示加载需要通过newInstance方法创建对象,并通过反射机制来设置对象的属性,如上文的反射例子所示。

loadClass与forName的区别

  • Class.forName得到的类是已经初始化完成的,ClassLoader.loadClass得到的类还未初始化完成;如下图的例子,forName加载的时候打印Shop中静态代码块中的"load Shop Class",loadClass无输出。
  • loadClass实现双亲委派机制,可以调用其他类的类加载器,forName调用当前类的类加载器

SpringIOC的lazyLoading, SpringIOC为了加快初始化的速度,大量使用延迟加载技术,用ClassLoader不需要进行初始化,可以加快加载速度,

package jvm.reflect;

//public class Shop {
//    private String name;
//    private int id;
//    private String getName(String head){
//        return head+" "+this.name;
//    }
//    public void outName(){
//        System.out.println(id+" "+this.name);
//    }
//    static{
//        System.out.println("load Shop Class");
//    }
//}

public class LoadTest {
    public static void main(String[] args) throws ClassNotFoundException {
//        Class r = Shop.class.getClassLoader().loadClass("jvm.reflect.Shop");
        Class r = Class.forName("jvm.reflect.Shop");
    }
}

相关文章

网友评论

      本文标题:类加载的两种方式:forName()和loadClass()详解

      本文链接:https://www.haomeiwen.com/subject/rkdvohtx.html