How to read the fully qualified name of a .class file

11,654

Solution 1

getClass().getName()

Update: You can load the class-file into a byte[] (using standard i/o) and then use getClass().getClassLoader().defineClass(...)

Solution 2

public String getFullClassName(String classFileName) throws IOException {           
        File file = new File(classFileName);

        FileChannel roChannel = new RandomAccessFile(file, "r").getChannel(); 
        ByteBuffer bb = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, (int)roChannel.size());         

        Class<?> clazz = defineClass((String)null, bb, (ProtectionDomain)null);
        return clazz.getName();
    }

Solution 3

Use a library like BCEL to read the classfile into memory and query it for the class name.

Solution 4

You can read this by parsing the binary. The class file format is defined in the VM Spec.

Have a look at the DataInputStream if you're new to parsing binaries.

Share:
11,654
TacB0sS
Author by

TacB0sS

A Java &amp; Android Developer/Architect and a ton of other things as well... Saved you an hour... buy me a coffee :)

Updated on July 24, 2022

Comments

  • TacB0sS
    TacB0sS almost 2 years

    Hey, I think the title sums it, but still.

    I need to extract the fully qualified name of an object from its compiled .class file, could anyone point me in the right direction?

    Thanks,
    Adam.

  • TacB0sS
    TacB0sS almost 14 years
    This is not the solution I had in mind, I would like to read it myself, thanks though.
  • TacB0sS
    TacB0sS almost 14 years
    not what I asked, I want to read the fqn from the .class file, the class object is not loaded into the memory.
  • TacB0sS
    TacB0sS almost 14 years
    that is nice, but I want this in runtime done by my application
  • Noon Silk
    Noon Silk almost 14 years
    @TaCB0sS That is reading the class name from the .class file. I think you don't understand your own question.
  • Tassos Bassoukos
    Tassos Bassoukos almost 14 years
    Then the answer from McDowell should point you to the right direction.
  • TacB0sS
    TacB0sS almost 14 years
    I do know what I want, I just didn't realize that a null can be passed to the defineClass. Thanks, Bozho!