views:

1371

answers:

5

Does anyone know how (or process) to remove comments from Java class file at build time? i would like to do this for specific packages in the project when the project is build using Ant. Any ANT scripts or some custom code most welcome.

+6  A: 

I believe the Java compiler does this for you already.

Andrew Hare
+12  A: 

There are no comments in the compiled .class file.

Bombe
+6  A: 

Class files don't have comments, they are removed by the compiler. If you want to strip comments from the source files, you could use ant's ReplaceRegExp task. But I'm curious as to why you would want to do this.

Jason Day
i thought comments get carried over to .class files. looking at way to reduce the size of my jar thats downloaded via webstart. Thanks.
n002213f
You could use the highest level of compression when creating the JAR file. That will make it a bit smaller.
Steve Kuo
See http://java.sun.com/j2se/1.5.0/docs/guide/deployment/deployment-guide/pack200.html . Pack200 can be challenging at first, but it dramatically decreases the size of your jars.
Jason Day
@JasonThanks for the packaging info
n002213f
A: 

the .class files don't normally include comments (you could actually store additional info about comments in there.. but AFAIK no one does that).

What is often present is the debug information containing the original variable names, source file information and line numbers information with the byte code. This can be controlled via the -g switch for javac or the debug attribute of the ant javac task.

fforw
+1  A: 

To shrink a Java jar file you can unset the -g flag to get rid of the debugging symbols, and you can run a code obfuscator. Code obfuscation is common in the J2ME world to minimize over-the-air download time to the phone. The downside to these steps is that it makes debugging much, much harder.

Jim Ferrans