gpt4 book ai didi

Java 自定义类加载器

转载 作者:行者123 更新时间:2023-12-01 19:22:29 25 4
gpt4 key购买 nike

有什么想法为什么我会收到此错误吗? (是的,我查了错误,仍然没有找到解决办法)

我的错误:

Exception in thread "main" java.lang.ClassFormatError: Truncated class file
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.lang.ClassLoader.defineClass(Unknown Source)
at org.fellixombc.mysql.util.MysqlClassLoader.findClass(MysqlClassLoader.java:22)
at org.fellixombc.mysql.util.MysqlClassLoader.loadClass(MysqlClassLoader.java:14)
at org.fellixombc.mysql.Main.main(Main.java:9)

文件:

Main.java

package org.fellixombc.mysql;

import org.fellixombc.mysql.util.MysqlClassLoader;

public class Main {
public static void main(String[] args) {
MysqlClassLoader mcl = new MysqlClassLoader();
try {
mcl.loadClass("org.fellixombc.mysql.net.Client");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}

客户端.java:

package org.fellixombc.mysql.net;

public class Client {
public Client() {
System.out.println("Hello!");
}
}

MysqlClassLoder.java:

package org.fellixombc.mysql.util;

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

public class MysqlClassLoader extends ClassLoader {
public MysqlClassLoader() {
super(MysqlClassLoader.class.getClassLoader());
}

@Override
public Class<?> loadClass(String className) throws ClassNotFoundException {
return findClass(className);
}

@Override
public Class<?> findClass(String className) throws ClassNotFoundException {
byte[] b = null;
try {
b = loadClassData(className);
Class c = defineClass(className, b, 0, b.length);
if(c != null)
return c;
return super.findClass(className);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

private byte[] loadClassData(String className) throws IOException {
int size = className.length();
byte buff[] = new byte[size];

// Open the file
FileInputStream fis = new FileInputStream("bin/" + className.replace('.', File.separatorChar) + ".class");
fis.available();
fis.read(buff);
fis.close();

return buff;
}
}

最佳答案

是的,您读取的字节数最多等于文件名中的字符数。相反,您需要读取整个文件。这是一种方法,按照您的建议使用 readFully。

File f = new File("bin/" + className.replace('.', File.separatorChar) + ".class");
DataInputStream is = new DataInputStream(new FileInputStream(f));
int len = (int)f.length();
byte[] buff = new byte[len];
is.readFully(buff);
is.close();
return buff;
<小时/>

由于您没有处理像 Object 这样的内置类,我认为您需要从 findClass 中的 loadClassData 捕获 FileNotFoundException,然后调用 super.findClass。例如:

try {
try {
b = loadClassData(className);
}
catch(FileNotFoundException fnf) {
return super.findClass(className);
}
Class c = defineClass(className, b, 0, b.length);
if(c != null)
return c;
return super.findClass(className);
} catch (IOException e) {
e.printStackTrace();
}
return null;

关于Java 自定义类加载器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3375825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com