Home >Java >javaTutorial >How to override findClass() method in Java?

How to override findClass() method in Java?

WBOY
WBOYforward
2023-04-22 22:40:221159browse

Method Description

1. Use the findClass(String) method to reload the class bytecode file, because in ClassLoader, the ffindClass method is modified by protected and can only call quilt The class has no implemented methods and only throws a ClassNotFoundException exception.

2. Rewrite the findClass method so that it can be called by external objects and class the logic code of the bytecode file.

Example

package com;
import java.io.InputStream;
import java.net.URL;
public class MyClassLoader extends ClassLoader{
    /**
     * 加载class文件
     * 重写此方法的目的是为了能让此方法被外部调用,父类的 findClass 是 protected 修饰的,只能被子类调用
     * @param name   类的全类名 示例: com.xd.User
     * @return
     * @throws ClassNotFoundException
     */
    @Override
    public Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            // 获取class文件名称  去掉包路径
            String fileName = name.substring(name.lastIndexOf(".") + 1) + ".class";
            // 获取文件输入流
            InputStream is = this.getClass().getResourceAsStream(fileName);
            // 读取字节
            byte[] b = new byte[is.available()];
            is.read(b);
            // 将byte字节流解析成jvm能够识别的Class对象
            return defineClass(name, b, 0, b.length);
        } catch (Exception e) {
            throw new ClassNotFoundException();
        }
    }
}

The above is the detailed content of How to override findClass() method in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete