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?
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)
The easiest way is probably using something like ASM:
If you can't use a 3rd party library, you could read the class file format yourself.
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.
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)
: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.