问题
在阅读tomcat 与 java web 开发技术详解 第三章 3.2.3时,发现对javac了解太浅。
Tomcat相当于一个jar包。用户在tomcat的指定目录下,编写符合selvert规范的应用代码类,现在需要编译。
DOS 到指定目录,javac编译
c:xxx> javac -classpath c:\xxx\servlet-api.jar -sourcepath src
-d WEB-INF\classes sec\mypack\DispatcherServlet.java
粗浅解答
- classpath 指定types that requires compile source file
- d 编译后的 .class 输出位置
- xxx.java 源文件
- sourcepath 设置这个option, 编译器就将在这个path下搜索文件。否则,编译就在class path 下搜索 class files 和 source files。
深入了解
格式
javac [options] [source-files]
Where [options] denotes the options controlling operations of the tool, and [source-files] indicates one or more source files to be compiled
所有的选项都是optional。源文件可以当成参数直接传给javac 命令。注意,源文件 Notice that source files should be arranged in a directory hierarchy corresponding to the fully qualified names of the types they contain.
javac 的options分为3种:standard, cross-compilation, extra. cross-compilation用的比较少。
Type的定义
假设有一个类
public class Data{
List<String> textList = new ArrayList();
public void addText(String text){
textList.add(text);
}
public List getTextList(){
return this.textList;
}
文件放在位置com/baeldung/javac/Data.java
standard options
最常用的standard options 是 -d
, 指定生成class 文件的目的地文件夹。如果 type 不属于默认的package, a directory structure reflecting the package’s name is created to keep the class file of that type。
javac -d javac-target com/baeldung/javac/Data.java
生成的class 文件在javac-target文件夹,最终为 javac-target/com/baeldung/javac/Data.class
- -cp(or -classpath, -class-path) 指定 需要编译source file的types的路径。如果这个命令缺失,或者CLASSPATH 环境变量没有设置,当前的工作路径就会被顶替使用。
- -p (or module-path) 暗示必要的模块路径。 这个命令只有在java9才有效。
如果想知道编译过程,可以使用-verbose
选项
最后一个标准option是关于参数文件。为了代替直接传参数给javac, 我们可以将他们存在一个参数文件中。在命令行中 @文件名
当javac遇见@,就会将后面的字符当做文件路径,然后去找到文件,将文件中的参数读取进来。 空格和换行可以用来区分两对不同的arguments.
options file
-d javac-target
-verbose
The types file :
com/baeldung/javac/Data.java
为了将两个文件中的命令读进来,可以使用
javac @javac-args/options @javac-args/types
或者存储在一个文件中,
javac-args
-d javac-target -verbose
com/baeldung/javac/Data.java
javac的命令行就是
javac @javac-args/arguments
这是最常用的标准命令,更全的列表在这里
Extra options
外部命令是非标准命令,会随着时间变化,在此就不一一列取。
但是值得一提的是,这些命令是userful。
- -Xlint 触发所有的推荐warnings
- -Xlint:key :
- rawtypes
- unchecked
- static
- cast
- serial
- fallthrough
输入输出
输入: source file (.java), 依赖的jar , jdk
输出: .class 文件
Reference
Compiling Java *.class Files with javac
java types
There are two types of data types in Java:
- Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double.
- Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.