我想在我的代码中使用bin文件夹中的.class文件 - 将其转换为字节,但不知道如何获取它。我有bin / example.class,我需要加载它并检查我的类有多少字节。
我找到了类似的东西:
public class MyClassLoader extends ClassLoader{
public MyClassLoader(){
super(MyClassLoader.class.getClassLoader());
}
}
但它似乎没有帮助,它必须是一些非常简单的方法来做到这一点。它看起来很容易,整个互联网试图让我写出千行classLoader代码。
编辑:我的java文件是以编程方式编译的.class文件是以编程方式创建的,所以我不能只是引用它的名字,它也是工作区中的其他地方。一些提示?
答案 0 :(得分:3)
只需将bin文件夹添加到类路径中即可!
要获取字节数,请获取资源URL,转换为File对象并查询大小。
示例:
package test;
import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;
public class Example {
public static final String NAME = Example.class.getSimpleName() + ".class";
public static void main(String[] args) throws URISyntaxException {
URL url = Example.class.getResource(NAME);
long size = new File(url.toURI().getPath()).length();
System.out.printf("The size of file '%s' is %d bytes\n", NAME, size);
}
}
将输出:
文件'Example.class'的大小是1461字节
答案 1 :(得分:1)
你可以这样做:
public class MyClassLoader extends ClassLoader {
protected synchronized Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException {
try {
return super.loadClass(name, resolve);
}
catch (ClassNotFoundException e) {
// TODO: test, if you can load the class with
// the given name. if not, rethrow the exception!
byte[] b = loadClassData(name);
return defineClass(name, b, 0, b.length);
}
}
private byte[] loadClassData(String name) {
// TODO: read contents of your file to byte array
}
}