Performing bytecode manipulation using APIs like javaassist modify class files after compilation. But, if the java code is optimized can't the modifications be performed in the wrong place? Are there ways to avoid this problem? Is the story any different between regular Java and Android?

- 42,759
- 13
- 108
- 192

- 213
- 1
- 6
-
3Bytecode is never optimized, at least not in important ways. – Marko Topolnik Jul 22 '15 at 14:52
-
I don't follow your exact meaning. You mean the conversion from .java to .class by javac doesn't involve much optimization? – Justin Watkins Jul 22 '15 at 14:55
-
1Yes, almost no optimization is performed in that step. It's mostly a straightforward translation. Actually, an attempt to optimize bytecode may ruin the JIT-compiler's optimizations and result in slower code. – Marko Topolnik Jul 22 '15 at 14:56
-
You mean obfuscate tool (like ProGuard)? – Toris Jul 22 '15 at 14:58
-
And, answering your title question, bytecode manipulation is not safe, you can always produce bytecode which is invalid and can cause JVM to crash during loading (or execution). – Grzesuav Jul 23 '15 at 13:44
1 Answers
A typical Java program is compiled multiple times. In a first step, Java source code is translated into Java byte code. In a second step, Java byte code is translated into machine code.
The details of this process are of course dependent on the virtual machine that runs code. Early versions of Java did for example not include a so-called just-in-time compiler. In this case, the byte code was interpreted instruction by instruction where byte code manipulations could of course have a performance impact. But this is not longer true. Both the OpenJDK's HotSpot virtual machine as well as Android's ART and DEX runtimes perform optimizations of the byte code.
The javac compiler that translates source code into byte code performs very few optimizations. You should not normally worry about the performance impact of the to-byte-code translation step. However, in some cases, the byte code that is produced by runtime code generation can have a performance impact. This happens when the just-in-time compiler observes byte code that is difficult to optimize. Typically, this is caused by unnecessary object allocations which are difficult to optimize away.
If you want to look in the details of this matter, I have given this presentation where I talk a bit about the problem: https://www.youtube.com/watch?v=XMY6HA7_h5Y
As for safety: As long as the byte code manipulation does not corrupt the byte code, there is no problem. If it does corrupt the byte code, the Java virtual machine will refuse loading the class with the corrupt code. This is both true for HotSpot and Android which verify any byte code previous to loading a class.

- 91
- 1
- 9

- 42,759
- 13
- 108
- 192