从字节码解析类名 [英] Resolve class name from bytecode

查看:123
本文介绍了从字节码解析类名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从类源代码中形成的字节码中挖掘出类名?

Is it possible to dig up a classes name from bytecode which is formed from the class' source code?

情况是这样的:我从某个地方远程获取一个类字节码,它来自哪里无关紧要。要使用类加载器有效地加载该类,我需要具有类名...对吗?

The situation is this: I get a classes bytecode remotely from somewhere, it doesn't matter where it comes from. To effectively load that class with a classloader i would need to have the class name as well... right?

推荐答案

如果你只需要类名,那么自己解析类文件的开头可能更容易,而不是添加第3个用于类代码操作的派对库就是为了这个目的。您只需要常量池中的类和字符串,跳过访问标志然后替换/。在班级名称中。如果你有一个字节数组,你可以用 new ByteArrayInputStream(byteArray)调用这个方法:

If you just need the class name, it's probably easier to parse the beginning of the class file yourself instead of adding a 3rd party library for class code manipulation just for this purpose. You just need the classes and strings from the constant pool, skip the access flags and then replace / with . in the class name. If you have a byte array, you can call this method with new ByteArrayInputStream(byteArray):

public static String getClassName(InputStream is) throws Exception {
    DataInputStream dis = new DataInputStream(is);
    dis.readLong(); // skip header and class version
    int cpcnt = (dis.readShort()&0xffff)-1;
    int[] classes = new int[cpcnt];
    String[] strings = new String[cpcnt];
    for(int i=0; i<cpcnt; i++) {
        int t = dis.read();
        if(t==7) classes[i] = dis.readShort()&0xffff;
        else if(t==1) strings[i] = dis.readUTF();
        else if(t==5 || t==6) { dis.readLong(); i++; }
        else if(t==8) dis.readShort();
        else dis.readInt();
    }
    dis.readShort(); // skip access flags
    return strings[classes[(dis.readShort()&0xffff)-1]-1].replace('/', '.');
}

这篇关于从字节码解析类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆