用javac编译生成不同版本的源码和目标class

合理使用javac的source和target选项, 可以使程序的兼容性得到提升.比如, 你写了某个方法, 命名为assert, 该source能通过1.3编译, 而后, 1.4将assert加入到了关键字列表.
此时, 你再用1.4编译时, 就会出错了.

同样地, 1.5之前因为没有引入enum关键字, 如果你的代码中使用了, 那在1.5之后编译就会错误.
解决这个问题的方法, 就是使用 source 选项. Javac -source 1.3 classFileName.-source 选项, 指定源码版本.

-target 选项, 指定目标class版本. 如果已经指定了source版本, 那target版本不能低于source.target选项也是一个对javac来说很灵活的设置.
你可以做到, 用低版本的source编译出高版本的class. 很有趣哦! 不同版本的javac, 默认source与target选项值

JDK/J2SDK Default Source Source Range Default Target Target Range
1.0.x 1.0 1.1
1.1.x 1.1 1.1
1.2.x 1.2 1.1 1.1 – 1.2
1.3.x 1.2/1.3 1.1 1.1 – 1.3
1.4.x 1.2/1.3 1.2? – 1.4 1.2 1.1 – 1.4
5 1.5 1.2 – 1.5 1.5 1.1 – 1.5
6 1.5 1.2 – 1.6 1.6 1.1 – 1.6
7 1.7 1.2 – 1.7 1.7 1.1 – 1.7


经过不同版本编译后的class文件版本, 各是多少呢?

Target Major.minor Description
1.1 45.3 The original shipped
version.
1.2 46.0 Supports
the strictfp modifier.
1.3 47.0 Small update.
1.4 48.0 Small update.
5 (1.5) 49.0 New
attributes
to support generics and other features. Many more strings
accepted as legal identifiers.
6 (1.6) 50.0 StackMaps are supported.
7 (1.7) 51.0 invokedynamic is
supported.

转载请注明原文链接:http://kenwublog.com/compile-various-versioned-class-with-javac

2009/08/06 | Posted in Development Skills
No comments yet.

Leave a comment

Attention: Java syntax highlighting is enable. For example: <pre lang="java"> class A {} </pre>