Minify Code - Java

2019-09-09 06:03发布

问题:

I was wondering if there is any tool to optimize/minify my Java Code. I already found out about some Obfuscators (http://java-source.net/open-source/obfuscators), but I'm not sure if this is what I want, because I actually want still "readable" Java FIles, but having it minified in sence of e.g. creating methods for code thats duplicated, just make the code better.

Is there any tool that can do that?

回答1:

There are toools that reformat your code, point out not-so-obvious mistakes or use compile-time code generation to make your code more readable. You should check out Lombok.

Still, probably the best way to reformat your code is doing it by yourself. Create a fair amount of unit tests so you can keep track of your methods' results and then you can reformat the code incrementally running the tests every now and then. This way it takes much less effort to change anything in your code - if your tests have good quality and coverage, after all the reformatting your code might look entirely different (the way you want it) and the methods' results will stay satisfactory.



回答2:

You're not looking for minification, you're looking for automatic refactoring. There's automated-refactoring for that. Additionally IDEs can assist you with semi-automatic refactoring and automatic reformattings that can also reduce lines of code.

static-analysis tools can help you to find potential code issues that need manual fixing. But since they have some false positives it would be dangerous to just apply their proposed fixes automatically.

Test coverage tools may also be helpful in finding unused code, assuming the tests are sufficiently comprehensive.



回答3:

I actually just released something a few days ago that does exactly this (for compiled java. At the source level all you can really do is formatting tricks). It's part of a multi-project repository I'm working on. Screenshot:

How it works: Using ASM (Bytecode modification library) classes are read and stripped of their debug info. Then the main class as given in the MANIFEST is visited. Each type that is referenced in the class is added to a list and are also visited. The process occurs recursively until everything that is referenced is on the list. Most of the time if you're using libraries there will be classes that are never referenced. Those are not on the list and when ASM recompiles the classes they are not included.

When running it on itself it dropped from roughly 700kb to roughly 150kb. Most of what was dropped was apache commons and some of my own files that weren't used by the shrinker.