I have a project with a folder "input" that contains a few java files(e.g. test.java).This folder is not a source root and that's right. I only want to analyze the files in the input folder with my program. One target is it to get the bytecode from the files in the input folder and save it in a string. I read a lot about getting bytecodes from classes(java agents,bcel) but it's not very clear to me how I should start. Do you have any ideas and tips for me ?
Edit: I compiled my files and saved it into a byte array. I used javaassist library as mentioned by someone. My code is now:
ClassPool pool = ClassPool.getDefault();
CtClass cc = pool.get("Test");
byte[] b = cc.toBytecode();
System.out.println(Arrays.toString(b));
As result I am getting:
[-54, -2, -70, -66, 0, 0, 0, 52, 0, 93, 10, 0, 25, 0, 52, 8, 0, 53, 7, 0,...,115]
How can I get from the byte array the "human readable" form of bytecode for example:
iconst_0 // 03
istore_0 // 3b
iinc 0, 1 // 84 00 01
iload_0 // 1a
iconst_2 // 05
imul // 68
istore_0 // 3b
goto -7 // a7 ff f9
Anyone has some idea?
"bytecode" refers to compiled classfiles. It doesn't make sense to ask how to get bytecode from a .java file because there is no bytecode to get. You need to compile them with javac, Eclipse, or similar. Then you can just read the resulting .class files any way you want.
Edit: To convert the classfile into a human readable form, you need a disassembler. A limited disassembler called javap is included in the JDK, so the simplest approach would be to just use that. Alternatively, you can use the Krakatau disassembler, which supports a lot more advanced features than javap.