2

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?

2
  • Well, guess what the JVM itself is doing? Correct, it interprets the bytecode and gets the class name from it :) Without giving a little bit more detail on what, how and (mainly) why you are trying to do this giving an answer is difficult Commented Oct 30, 2009 at 13:01
  • Yeah, yeah, noted... I would like to get the name of the class at runtime so i can dynamically load the class with a classloader, since you need to specify the name and classpath of the class you're loading. Commented Oct 30, 2009 at 13:10

6 Answers 6

12

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('/', '.');
}
Sign up to request clarification or add additional context in comments.

14 Comments

Great, thanks! Sounds like a solid solution. I won't have a chance to try it out immediately, but i trust this works. "Can't programmers program anymore and are they just..." To a large extent, yes ;) Many of todays "coders" are not so much coders as they are integrators of libraries. Plus (especially with this task) to produce an error free solution would require a lot of work and study as i'm not at all familiar with Java bytecode. But thanks!
BE CAREFUL with the code given in this example. While it works for many class files, it throws an exception (ArrayIndexOutOfBoundsException) for others. This is actually a great example why sometimes using a well-tested library is better than doing it yourself.
Typeracer is right. It looks like it fails for code with INVOKEDYNAMIC -- something with lambdas-related, or with boostrap entries inside constant pool
@typeracer the main problem with this code is not that it is not up-to-date, but that it does neither, check the file’s version number nor report unknown tags, but rather treats everything unknown as if having four bytes to skip. This answer happens to solve the same task, but is up-to-date and even better, would report unknown tags and is easier to update, due to named constants.
By the way, DataInputStream has a method readUnsignedShort() since day one, so there never was a need to repeatedly write readShort()&0xffff.
|
2

The easiest way is probably using something like ASM:

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.commons.EmptyVisitor;

public class PrintClassName {
  public static void main(String[] args) throws IOException {
    class ClassNamePrinter extends EmptyVisitor {
      @Override
      public void visit(int version, int access, String name, String signature,
          String superName, String[] interfaces) {
        System.out.println("Class name: " + name);
      }
    }

    InputStream binary = new FileInputStream(args[0]);
    try {
      ClassReader reader = new ClassReader(binary);
      reader.accept(new ClassNamePrinter(), 0);
    } finally {
      binary.close();
    }
  }
}

If you can't use a 3rd party library, you could read the class file format yourself.

Comments

2

Just for completeness, in cases where the use of ASM5 library is acceptable, the following call could be used to obtain the class name from its byte representation.

public String readClassName(final byte[] typeAsByte) {
    return new ClassReader(typeAsByte).getClassName().replace("/", ".");
}

Comments

1

You should be able to use javap to disassemble the byte code, if that just happens once in a while.

For doing it at runtime: use a byte-code manipulation library like Apache's BCEL (http://jakarta.apache.org/bcel) to analyse the byte code.

2 Comments

Is there no built-in functionality for this?
@JHollanti - what you want is backwards from the way things are usually done - you start with a name (often from a descriptor file) and then use path conventions to load the class bytes. There is no standard way to load and run multiple arbitrary classes (which one would be the entry point? etc.)
1

Inspired by the solution provided by McDowell I created an updated version that works up to Java 19.

String getBinaryName(byte[] byteCode) {
        try (final var is = new DataInputStream(new ByteArrayInputStream(byteCode))) {
            final var magic = is.readInt();
            if (magic != 0xCAFEBABE) {
                throw new RuntimeException("Class file header is missing.");
            }
            
            final var minor = is.readUnsignedShort();
            final var major = is.readUnsignedShort();
            final int constantPoolCount = is.readShort();
            final var classes = new int[constantPoolCount - 1];
            final var strings = new String[constantPoolCount - 1];
            for (int i = 0; i < constantPoolCount - 1; i++) {
                int t = is.read();
                switch (t) {
                    case 1://utf-8
                        strings[i] = is.readUTF();
                        break;
                    case 3://Integer
                        is.readInt();
                        break;
                    case 4: // float
                        is.readFloat();
                        break;
                    case 5: // Long
                        is.readLong();
                        i++;
                        break;
                    case 6: // Double
                        is.readDouble();
                        i++;
                        break;
                    case 7: // Class index
                        classes[i] = is.readUnsignedShort();
                        break;
                    case 8: // string index
                        is.readShort();
                        break;
                    case 9: // field ref
                    case 10: // method ref
                    case 11: // interface method ref
                    case 12: // name and type
                    case 18: // invoke dynamic
                        is.readUnsignedShort();
                        is.readUnsignedShort();
                        break;
                    case 15: // method handle
                        is.read();
                        is.readUnsignedShort();
                        break;
                    case 16: // method type
                        is.readUnsignedShort();
                        break;
                    default:
                        throw new RuntimeException(format("Invalid constant pool tag %d at position %d", t,i));
                }
            }
            is.readShort(); // skip access flags
            final var classNameIndex = is.readShort();
            return strings[classes[(classNameIndex & 0xffff) - 1] - 1].replace('/', '.');
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

Comments

0

I think you can use the ClassLoader.defineClass method, in a subclass of ClassLoader, to get the Class object for a given bytecode. (not tested)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.