Home > Java > javaTutorial > body text

How to override findClass() method in Java?

WBOY
Release: 2023-04-22 22:40:22
forward
1144 people have browsed it

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();
        }
    }
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template