1

I have a byte[] that represents HelloWorld.class now I want to convert into say a String that represents a bytecode(similar to javap -c HelloWorld.class)? And I want to do this programmatically.

Simply put I want to go from

byte[] to String that represents javap -c HelloWorld.class

and

bytecode String back to byte[]

Note: All done programatically so I dont want to invoke anything through command line

Open to any well known standard libraries like asm or bytebuddy.

user1870400
  • 6,028
  • 13
  • 54
  • 115
  • 2
    This seems to be an answer: https://stackoverflow.com/a/14451505/547270 – scrutari Oct 29 '18 at 08:04
  • "Open to any well known standard libraries" Questions asking for library recommendations are off-topic for StackOverflow. – Michael Oct 29 '18 at 08:16
  • @Michael they weren't asking for a library recommendation, they were asking for a solution and stating that there were no constraints on what library to use. – Michael Kay Oct 29 '18 at 12:46
  • The problem statement is not entirely clear. Does the `byte[]` contain the *whole class file data*, or only the data from the [code attribute](https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.3)? The main issue is: The output of `javap` is not "reversible" in that sense. You cannot create a full-fledged Java class from the `javap` output. – Marco13 Oct 29 '18 at 13:28
  • Well, how complicated should it be? How about just writing the bytes to a temporary file and actually running `javap` as sub-process? With recent Java versions, it’s close to a one-liner… – Holger Oct 29 '18 at 19:05

1 Answers1

0

Using ASM, try creating a ClassReader over the byte[] representation of the class, then calling ClassReader.accept(), supplying a TraceClassVisitor as the ClassVisitor argument.

(Not tested. We use most of these components, but not in quite this combination.)

Michael Kay
  • 156,231
  • 11
  • 92
  • 164