如何实现一个Java类加载器

本文深入探讨了Java中自定义ClassLoader的实现方式,通过创建CustomClassLoader类来加载Main.java,展示了不同类加载器间的命名空间差异,并解析了加载java.lang.System类的限制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 我的包的路径是com.company.*

新建两个文件,一个Main.java,用作被加载之用。

一个CustomClassLoader.java,用于加载Main.java。

代码如下:

package com.company;

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

public class CustomClassLoader extends ClassLoader {
    @Override
    public Class findClass(String name) throws ClassNotFoundException {
        byte[] b = loadClassFromFile(name);
        return defineClass(name, b, 0, b.length);
    }

    private byte[] loadClassFromFile(String fileName)  {
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream(
                fileName.replace('.', File.separatorChar) + ".class");
        byte[] buffer;
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        int nextValue = 0;
        try {
            while ( (nextValue = inputStream.read()) != -1 ) {
                byteStream.write(nextValue);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        buffer = byteStream.toByteArray();
        return buffer;
    }

    public static void main(String[] args) {
        CustomClassLoader customClassLoader = new CustomClassLoader();
        try {
            Object main = customClassLoader.findClass("com.company.Main").newInstance(); //com.company.CustomClassLoader@511d50c0
            System.out.println(main.getClass().getClassLoader());//sun.misc.Launcher$AppClassLoader@18b4aac2
            System.out.println(Main.class.getClassLoader());//false
            System.out.println(main instanceof Main);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

可以看到指定使用CustomClassLoader和使用JVM默认的方式加载的Main是会被判断为不是同一类的。

因为不同的类加载器有不同的命名空间。

https://www.baeldung.com/java-classloaders

另外经常会有面试题问能够自己定义一个java.lang.System进行加载,答案是否定的

我们可以尝试在src目录下新建java.lang.System类,再用上面的代码尝试加载,会发现抛出异常java.lang.SecurityException: Prohibited package name: java.lang。

在ClassLoader类中也可以看到这样的解释。

*          If an attempt is made to add this class to a package that
*          contains classes that were signed by a different set of
*          certificates than this class, or if an attempt is made
*          to define a class in a package with a fully-qualified name
*          that starts with "{@code java.}".
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值