学习 java命令

依稀记得自己第一次编译*.java文件,第一次运行*.class文件。但是六七年过去了,现在运行java写的程序更多的是用tomcat这种web容器。最近有个小需求,写一个监控zookeeper集群的报警器,当发现集群中节点发生变化时,发出邮件和短信通知运维人员。如果这么一个功能也写成一个web项目放到tomcat里,就有些杀鸡用牛刀了。于是就写了一个jar项目,用 java -jar 运行。占用资源少不说,部署启动很简单,也不占用访问端口。但也遇到了很多问题,才发现自己对java命令还是一知半解。写篇文章,一点一滴的记录一下如何使用java命令。

JDK下的命令

先来看看JDK下有哪些命令。

> cd $JAVA_HOME/bin
> pwd
/Library/Java/JavaVirtualMachines/jdk1.7.0_75.jdk/Contents/Home/bin
> ls
appletviewer   javafxpackager jmc            native2ascii   servertool
apt            javah          jps            orbd           tnameserv
extcheck       javap          jrunscript     pack200        unpack200
idlj           jcmd           jsadebugd      policytool     wsgen
jar            jconsole       jstack         rmic           wsimport
jarsigner      jdb            jstat          rmid           xjc
java           jhat           jstatd         rmiregistry
javac          jinfo          jvisualvm      schemagen
javadoc        jmap           keytool        serialver
 

目测我只会javac、java、javadoc、jar其他的就不知道了,木有关系,从现在开始,一个一个百度谷歌弄都了就好。我相信弄懂后不出一个月我就又会忘记,学习本身就是这样,学的多忘的多,但为了保持学习能力一定要不停的学^_^。

javac

javac主要是将*.java文件编译成*.class文件。*.class文件就可以放到java虚拟机里运行了。其实编译的过程就是将人能看懂的东西转换成机器能看懂的东西。

敲一下命令看看有啥操作参数.

> javac -help
用法: javac <options> <source files>
其中, 可能的选项包括:
  -g                         生成所有调试信息
  -g:none                    不生成任何调试信息
  -g:{lines,vars,source}     只生成某些调试信息
  -nowarn                    不生成任何警告
  -verbose                   输出有关编译器正在执行的操作的消息
  -deprecation               输出使用已过时的 API 的源位置
  -classpath <路径>            指定查找用户类文件和注释处理程序的位置
  -cp <路径>                   指定查找用户类文件和注释处理程序的位置
  -sourcepath <路径>           指定查找输入源文件的位置
  -bootclasspath <路径>        覆盖引导类文件的位置
  -extdirs <目录>              覆盖所安装扩展的位置
  -endorseddirs <目录>         覆盖签名的标准路径的位置
  -proc:{none,only}          控制是否执行注释处理和/或编译。
  -processor <class1>[,<class2>,<class3>...] 要运行的注释处理程序的名称; 绕过默认的搜索进程
  -processorpath <路径>        指定查找注释处理程序的位置
  -d <目录>                    指定放置生成的类文件的位置
  -s <目录>                    指定放置生成的源文件的位置
  -implicit:{none,class}     指定是否为隐式引用文件生成类文件
  -encoding <编码>             指定源文件使用的字符编码
  -source <发行版>              提供与指定发行版的源兼容性
  -target <发行版>              生成特定 VM 版本的类文件
  -version                   版本信息
  -help                      输出标准选项的提要
  -A关键字[=值]                  传递给注释处理程序的选项
  -X                         输出非标准选项的提要
  -J<标记>                     直接将 <标记> 传递给运行时系统
  -Werror                    出现警告时终止编译
  @<文件名>                     从文件读取选项和文件名

再来看看扩展的操作有哪些。

> javac -X
  -Xlint                     启用建议的警告
  -Xlint:{all,cast,classfile,deprecation,dep-ann,divzero,empty,fallthrough,finally,options,overrides,path,processing,rawtypes,serial,static,try,unchecked,varargs,-cast,-classfile,-deprecation,-dep-ann,-divzero,-empty,-fallthrough,-finally,-options,-overrides,-path,-processing,-rawtypes,-serial,-static,-try,-unchecked,-varargs,none} 启用或禁用特定的警告
  -Xbootclasspath/p:<路径>     置于引导类路径之前
  -Xbootclasspath/a:<路径>     置于引导类路径之后
  -Xbootclasspath:<路径>       覆盖引导类文件的位置
  -Djava.ext.dirs=<目录>       覆盖所安装扩展的位置
  -Djava.endorsed.dirs=<目录>  覆盖签名的标准路径的位置
  -Xmaxerrs <编号>             设置要输出的错误的最大数目
  -Xmaxwarns <编号>            设置要输出的警告的最大数目
  -Xstdout <文件名>             重定向标准输出
  -Xprint                    输出指定类型的文本表示
  -XprintRounds              输出有关注释处理循环的信息
  -XprintProcessorInfo       输出有关请求处理程序处理哪些注释的信息
  -Xprefer:{source,newer}    指定读取文件, 当同时找到隐式编译类的源文件和类文件时
  -Xpkginfo:{always,legacy,nonempty} 指定 package-info 文件的处理

这些选项都是非标准选项, 如有更改, 恕不另行通知。

说实话,看着挺枯燥,里面知道怎么用的还是知道,不知道的,看完还是不知道。我们还是来看看man怎么说。

>man javac
Name
       javac - Java programming language compiler
SYNOPSIS

               javac [ options ] [ sourcefiles ] [ classes ] [ @argfiles ]

       Arguments may be in any order.
          options
             Command-line options.

          sourcefiles
             One or more source files to be compiled (such as MyClass.java).

          classes
             One  or  more  classes  to  be processed for annotations (such as
             MyPackage.MyClass).

          @argfiles
             One or more files that lists options and  source  files.  The  -J
             options are not allowed in these files.

DESCRIPTION

       The  javac  tool  reads class and interface definitions, written in the
       Java programming language, and compiles them into bytecode class files.
       It can also process annotations in Java source files and classes.
       There are two ways to pass source code file names to javac:
          o For  a small number of source files, simply list the file names on
            the command line.

          o For a large number of source files, list the file names in a file,
            separated by blanks or line breaks. Then use the list file name on
            the javac command line, preceded by an @ character.

       Source code file names must have .java suffixes, class file names  must
       have  .class  suffixes,  and both source and class files must have root
       names that identify the class. For  example,  a  class  called  MyClass
       would be written in a source file called MyClass.java and compiled into
       a bytecode class file called MyClass.class.
       Inner class definitions produce additional  class  files.  These  class
       files  have  names  combining  the inner and outer class names, such as
       MyClass$MyInnerClass.class.
       You should arrange source files in a directory tree that reflects their
       package  tree.  For  example,  if  you  keep  all  your source files in
       /workspace, the source code for com.mysoft.mypack.MyClass should be  in
       /workspace/com/mysoft/mypack/MyClass.java.
       By  default, the compiler puts each class file in the same directory as
       its source file. You can specify a separate destination directory  with
       -d (see Options, below).
OPTIONS

       The  compiler  has  a set of standard options that are supported on the
       current  development  environment  and  will  be  supported  in  future
       releases. An additional set of non-standard options are specific to the
       current virtual machine and compiler implementations and are subject to
       change in the future. Non-standard options begin with -X.
   Standard Options
          -Akey[=value]
             Options  to  pass  to annotation processors. These are not inter-
             preted by javac directly, but are made available for use by indi-
             vidual  processors.  key  should be one or more identifiers sepa-
             rated by ".".

          -cp path or -classpath path
             Specify where to find user class files, and (optionally)  annota-
             tion  processors  and source files. This class path overrides the
             user class path in the CLASSPATH environment variable. If neither
             CLASSPATH,  -cp  nor -classpath is specified, the user class path
             consists of the current directory. See Setting the Class Path for
             more details.
             >If  the -sourcepath option is not specified, the user class path
             is also searched for source files.
             If the -processorpath option is not specified, the class path  is
             also searched for annotation processors.

          -Djava.ext.dirs=directories
             Override the location of installed extensions.

          -Djava.endorsed.dirs=directories
             Override the location of endorsed standards path.

          -d directory
             Set the destination directory for class files. The directory must
             already exist; javac will not create it. If a class is part of  a
             package,  javac  puts the class file in a subdirectory reflecting
             the package name, creating directories as needed. For example, if
             you   specify   -d   /home/myclasses  and  the  class  is  called
             com.mypackage.MyClass,   then   the   class   file   is    called
             /home/myclasses/com/mypackage/MyClass.class.
             If  -d  is not specified, javac puts each class files in the same
             directory as the source file from which it was generated.
             Note: The directory specified by -d is not automatically added to
             your user class path.

          -deprecation
             Show a description of each use or override of a deprecated member
             or class. Without -deprecation, javac  shows  a  summary  of  the
             source  files that use or override deprecated members or classes.
             -deprecation is shorthand for -Xlint:deprecation.

          -encoding encoding
             Set the source file encoding name, such as EUC-JP and  UTF-8.  If
             -encoding  is  not  specified,  the platform default converter is
             used.

          -endorseddirs directories
             Override the location of endorsed standards path.

          -extdirs directories
             Overrides the location of  the  ext  directory.  The  directories
             variable  is  a colon-separated list of directories. Each JAR ar-
             chive in the specified directories is searched for  class  files.
             All  JAR archives found are automatically part of the class path.
             If you are cross-compiling (compiling classes  against  bootstrap
             and  extension  classes  of a different Java platform implementa-
             tion), this option specifies the  directories  that  contain  the
             extension  classes. See Cross-Compilation Options for more infor-
             mation.

          -g Generate all debugging information, including local variables. By
             default,  only  line number and source file information is gener-
             ated.

          -g:none
             Do not generate any debugging information.

          -g:{keyword list}
             Generate only some kinds of debugging information, specified by a
             comma separated list of keywords. Valid keywords are:

             source
                Source file debugging information

             lines
                Line number debugging information

             vars
                Local variable debugging information

          -help
             Print a synopsis of standard options.

          -implicit:{class,none}
             Controls  the  generation  of  class  files for implicitly loaded
             source  files.  To  automatically  generate  class   files,   use
             -implicit:class.   To   suppress   class   file  generation,  use
             -implicit:none. If this option is not specified, the  default  is
             to automatically generate class files. In this case, the compiler
             will issue a warning if any such class files are  generated  when
             also  doing annotation processing. The warning will not be issued
             if this option is set explicitly. See Searching For Types.

          -Joption
             Pass option to the java launcher called by  javac.  For  example,
             -J-Xms48m sets the startup memory to 48 megabytes. It is a common
             convention for -J to pass options to the underlying VM  executing
             applications written in Java.
             Note:  CLASSPATH, -classpath, -bootclasspath, and -extdirs do not
             specify the classes used to run javac. Fiddling with  the  imple-
             mentation  of  the  compiler in this way is usually pointless and
             always risky. If you do need to do this, use  the  -J  option  to
             pass through options to the underlying java launcher.

          -nowarn
             Disable   warning   messages.   This  has  the  same  meaning  as
             -Xlint:none.

          -proc: {none,only}
             Controls whether  annotation  processing  and/or  compilation  is
             done. -proc:none means that compilation takes place without anno-
             tation processing. -proc:only means that only annotation process-
             ing is done, without any subsequent compilation.

          -processor class1[,class2,class3...]
             Names  of  the  annotation  processors  to run. This bypasses the
             default discovery process.

          -processorpath path
             Specify where to find annotation processors; if  this  option  is
             not used, the class path will be searched for processors.

          -s dir
             Specify  the directory where to place generated source files. The
             directory must already exist; javac will  not  create  it.  If  a
             class  is part of a package, the compiler puts the source file in
             a subdirectory reflecting the package name, creating  directories
             as  needed.  For  example,  if you specify -s /home/mysrc and the
             class is called com.mypackage.MyClass, then the source file  will
             be placed in /home/mysrc/com/mypackage/MyClass.java.

          -source release
             Specifies the version of source code accepted. The following val-
             ues for release are allowed:

             1.3
                The compiler does not support assertions, generics,  or  other
                language features introduced after Java SE 1.3.

             1.4
                The  compiler  accepts  code containing assertions, which were
                introduced in Java SE 1.4.

             1.5
                The compiler accepts code containing generics and  other  lan-
                guage features introduced in Java SE 5.

             5  Synonym for 1.5.

             1.6
                No  language  changes  were  introduced in Java SE 6. However,
                encoding errors in source files are  now  reported  as  errors
                instead of warnings as in previous releases of Java SE.

             6  Synonym for 1.6.

             1.7
                This is the default value. The compiler accepts code with fea-
                tures introduced in Java SE 7.

             7  Synonym for 1.7.

          -sourcepath sourcepath
             Specify the source code path to search  for  class  or  interface
             definitions. As with the user class path, source path entries are
             separated by colons (:) and can be directories, JAR archives,  or
             ZIP  archives.  If  packages are used, the local path name within
             the directory or archive must reflect the package name.
             Note: Classes found through the class  path  may  be  subject  to
             automatic  recompilation  if  their  sources  are also found. See
             Searching For Types.

          -verbose
             Verbose output. This includes information about each class loaded
             and each source file compiled.

          -version
             Print version information.

          -Werror
             Terminate compilation if warnings occur.

          -X Display information about non-standard options and exit.

   Cross-Compilation Options
       By  default,  classes  are compiled against the bootstrap and extension
       classes of the platform that javac shipped with. But  javac  also  sup-
       ports  cross-compiling,  where classes are compiled against a bootstrap
       and extension classes of a different Java platform  implementation.  It
       is  important  to use -bootclasspath and -extdirs when cross-compiling;
       see Cross-Compilation Example below.
          -target version
             Generate class files that target a specified version of  the  VM.
             Class  files  will  run on the specified target and on later ver-
             sions, but not on earlier versions of the VM. Valid  targets  are
             1.1, 1.2, 1.3, 1.4, 1.5 (also 5), 1.6 (also 6), and 1.7 (also 7).

          The default for -target depends on the value of -source:

             o If -source is not specified, the value of -target is 1.7

             o If -source is 1.2, the value of -target is 1.4

             o If -source is 1.3, the value of -target is 1.4

             o If -source is 1.5, the value of -target is 1.7

             o If -source is 1.6, the value of -target is 1.7

             o For all other values of -source, the value of  -target  is  the
               value of -source.

          -bootclasspath bootclasspath
             Cross-compile  against the specified set of boot classes. As with
             the user class path, boot class path  entries  are  separated  by
             colons (:) and can be directories, JAR archives, or ZIP archives.

   Non-Standard Options
          -Xbootclasspath/p:path
             Prepend to the bootstrap class path.

          -Xbootclasspath/a:path
             Append to the bootstrap class path.

          -Xbootclasspath/:path
             Override location of bootstrap class files.

          -Xlint
             Enable all recommended warnings. In this  release,  enabling  all
             available warnings is recommended.

          -Xlint:all
             Enable  all  recommended  warnings. In this release, enabling all
             available warnings is recommended.

          -Xlint:none
             Disable all warnings.

          -Xlint:name
             Enable warning name. See the section Warnings That Can Be Enabled
             or  Disabled  with  -Xlint  Option for a list of warnings you can
             enable with this option.

          -Xlint:-name
             Disable warning name.  See  the  section  Warnings  That  Can  Be
             Enabled or Disabled with -Xlint Option for a list of warnings you
             can disable with this option.

          -Xmaxerrs number
             Set the maximum number of errors to print.

          -Xmaxwarns number
             Set the maximum number of warnings to print.

          -Xstdout filename
             Send compiler messages to the named file.  By  default,  compiler
             messages go to System.err.

          -Xprefer:{newer,source}
             Specify which file to read when both a source file and class file
             are found for a  type.  (See  Searching  For  Types).  If  -Xpre-
             fer:newer is used, it reads the newer of the source or class file
             for a type (default). If the -Xprefer:source option is  used,  it
             reads  source  file. Use -Xprefer:source when you want to be sure
             that any annotation processors can  access  annotations  declared
             with a retention policy of SOURCE.

          -Xpkginfo:{always,legacy,nonempty}
             Specify handling of package-info files

          -Xprint
             Print out textual representation of specified types for debugging
             purposes; perform neither annotation processing nor  compilation.
             The format of the output may change.

          -XprintProcessorInfo
             Print information about which annotations a processor is asked to
             process.

          -XprintRounds
             Print information about initial and  subsequent  annotation  pro-
             cessing rounds.

   Warnings That Can Be Enabled or Disabled with -Xlint Option
       Enable  warning  name with the option -Xlint:name, where name is one of
       the following warning names. Similarly, you can  disable  warning  name
       with the option -Xlint:-name:
          cast
             Warn about unnecessary and redundant casts. For example:
             String s = (String)"Hello!"

          classfile
             Warn about issues related to classfile contents.

          deprecation
             Warn about use of deprecated items. For example:
                 java.util.Date myDate = new java.util.Date();
                 int currentDay = myDate.getDay();
             The  method  java.util.Date.getDay  has been deprecated since JDK
             1.1.

          dep-ann
             Warn about items that are documented with an @deprecated  Javadoc
             comment, but do not have a @Deprecated annotation. For example:
               /**
                * @deprecated As of Java SE 7, replaced by {@link #newMethod()}
                */

               public static void deprecatedMethood() { }

               public static void newMethod() { }

          divzero
             Warn about division by constant integer 0. For example:
                 int divideByZero = 42 / 0;

          empty
             Warn about empty statements after if statements. For example:
             class E {
                 void m() {
                     if (true) ;
                 }
             }

          fallthrough
             Check  switch blocks for fall-through cases and provide a warning
             message for any that are found. Fall-through cases are cases in a
             switch  block,  other than the last case in the block, whose code
             does not include a break statement, allowing  code  execution  to
             "fall  through" from that case to the next case. For example, the
             code following the case 1 label in this switch block does not end
             with a break statement:
             switch (x) {
             case 1:
                    System.out.println("1");
                    //  No break statement here.
             case 2:
                    System.out.println("2");
             }
             If  the  -Xlint:fallthrough  flag  were  used when compiling this
             code,  the  compiler  would  emit  a  warning   about   "possible
             fall-through  into  case," along with the line number of the case
             in question.

          finally
             Warn about finally clauses that  cannot  complete  normally.  For
             example:
               public static int m() {
                 try {
                   throw new NullPointerException();
                 } catch (NullPointerException e) {
                   System.err.println("Caught NullPointerException.");
                   return 1;
                 } finally {
                   return 0;
                 }
               }
             The  compiler generates a warning for finally block in this exam-
             ple. When this method is called, it returns a value of 0, not  1.
             A finally block always executes when the try block exits. In this
             example, if control is transferred to the catch, then the  method
             exits. However, the finally block must be executed, so it is exe-
             cuted, even though control has already been  transferred  outside
             the method.

          options
             Warn  about  issues  relating to the use of command line options.
             See Cross-Compilation Example for an  example  of  this  kind  of
             warning.

          overrides
             Warn  about  issues regarding method overrides. For example, con-
             sider the following two classes:
             public class ClassWithVarargsMethod {
               void varargsMethod(String... s) { }
             }
             public class ClassWithOverridingMethod extends ClassWithVarargsMethod {
               @Override
               void varargsMethod(String[] s) { }
             }
             The compiler generates a warning similar to the following:
             warning: [override] varargsMethod(String[]) in  ClassWithOverrid-
             ingMethod   overrides   varargsMethod(String...)   in  ClassWith-
             VarargsMethod; overriding method is missing ‘...‘
             When the compiler encounters a varargs method, it translates  the
             varargs  formal parameter into an array. In the method ClassWith-
             VarargsMethod.varargsMethod, the compiler translates the  varargs
             formal  parameter String... s to the formal parameter String[] s,
             an array, which matches the formal parameter of the method Class-
             WithOverridingMethod.varargsMethod.  Consequently,  this  example
             compiles.

          path
             Warn about invalid path elements and nonexistent path directories
             on  the  command line (with regards to the class path, the source
             path, and other paths). Such warnings cannot be  suppressed  with
             the @SuppressWarnings annotation. For example:
             javac -Xlint:path -classpath /nonexistentpath Example.java

          processing
             Warn  about  issues regarding annotation processing. The compiler
             generates this warning if you have a class that  has  an  annota-
             tion, and you use an annotation processor that cannot handle that
             type of exception. For example, the following is a simple annota-
             tion processor:
             Source file AnnoProc.java:
             import java.util.*;
             import javax.annotation.processing.*;
             import javax.lang.model.*;
             import javax.lang.model.element.*;

             @SupportedAnnotationTypes("NotAnno")
             public class AnnoProc extends AbstractProcessor {
                 public boolean process(Set<? extends TypeElement> elems, RoundEnvironment renv) {
                     return true;
                 }

                 public SourceVersion getSupportedSourceVersion() {
                     return SourceVersion.latest();
                 }
             }
             Source file AnnosWithoutProcessors.java:
             @interface Anno { }

             @Anno
             class AnnosWithoutProcessors { }
             The following commands compile the annotation processor AnnoProc,
             then run  this  annotation  processor  against  the  source  file
             AnnosWithoutProcessors.java:
             % javac AnnoProc.java
             % javac -cp . -Xlint:processing -processor AnnoProc -proc:only AnnosWithoutProcessors.java
             When  the  compiler  runs  the  annotation  processor against the
             source file AnnosWithoutProcessors.java, it generates the follow-
             ing warning:
             warning:  [processing]  No processor claimed any of these annota-
             tions: Anno
             To resolve this issue, you can rename the annotation defined  and
             used in the class AnnosWithoutProcessors from Anno to NotAnno.

          rawtypes
             Warn  about  unchecked  operations  on  raw  types. The following
             statement generates a rawtypes warning:
             void countElements(List l) { ... }
             The following does not generate a rawtypes warning:
             void countElements(List<?> l) { ... }
             List is a raw type. However,  List<?>  is  a  unbounded  wildcard
             parameterized  type.  Because  List is a parameterized interface,
             you should always specify its type argument. In this example, the
             List  formal  argument is specified with a unbounded wildcard (?)
             as its formal type parameter, which means that the  countElements
             method can accept any instantiation of the List interface.

          serial
             Warn  about  missing serialVersionUID definitions on serializable
             classes. For example:
             public class PersistentTime implements Serializable
             {
               private Date time;

                public PersistentTime() {
                  time = Calendar.getInstance().getTime();
                }

                public Date getTime() {
                  return time;
                }
             }
             The compiler generates the following warning:
             warning: [serial] serializable class PersistentTime has no  defi-
             nition of serialVersionUID
             If a serializable class does not explicitly declare a field named
             serialVersionUID, then the serialization runtime will calculate a
             default  serialVersionUID  value  for that class based on various
             aspects of the class, as described in the Java Object  Serializa-
             tion  Specification. However, it is strongly recommended that all
             serializable classes explicitly declare  serialVersionUID  values
             because  the  default process of computing serialVersionUID vales
             is highly sensitive to class details that may vary  depending  on
             compiler  implementations,  and  can  thus  result  in unexpected
             InvalidClassExceptions  during  deserialization.  Therefore,   to
             guarantee  a  consistent  serialVersionUID value across different
             Java compiler implementations, a serializable class must  declare
             an explicit serialVersionUID value.

          static
             Warn about issues relating to use of statics. For example:
             class XLintStatic {
                 static void m1() { }
                 void m2() { this.m1(); }
             }
             The compiler generates the following warning:
             warning: [static] static method should be qualified by type name, XLintStatic, instead of by an expression
             To  resolve this issue, you can call the static method m1 as fol-
             lows:
             XLintStatic.m1();
             Alternatively, you can remove the static keyword from the  decla-
             ration of the method m1.

          try
             Warn  about  issues  relating  to  use  of  try blocks, including
             try-with-resources statements. For example, a warning  is  gener-
             ated for the following statement because the resource ac declared
             in the try statement is not used:
             try ( AutoCloseable ac = getResource() ) {
                 // do nothing
             }

          unchecked
             Give more detail for unchecked conversion warnings that are  man-
             dated by the Java Language Specification. For example:
                 List l = new ArrayList<Number>();
                 List<String> ls = l;       // unchecked warning
             During type erasure, the types ArrayList<Number> and List<String>
             become ArrayList and List, respectively.
             The variable ls has the parameterized type List<String>. When the
             List referenced by l is assigned to ls, the compiler generates an
             unchecked warning; the compiler is unable to determine at compile
             time,  and moreover knows that the JVM will not be able to deter-
             mine at runtime, if l refers to a List<String> type; it does not.
             Consequently, heap pollution occurs.
             In detail, a heap pollution situation occurs when the List object
             l, whose static type is List<Number>, is assigned to another List
             object,  ls, that has a different static type, List<String>. How-
             ever, the compiler still allows this assignment.  It  must  allow
             this assignment to preserve backwards compatibility with versions
             of Java SE that do not support generics. Because of type erasure,
             List<Number> and List<String> both become List. Consequently, the
             compiler allows the assignment of the object l, which has  a  raw
             type of List, to the object ls.

          varargs
             Warn about unsafe usages of variable arguments (varargs) methods,
             in particular, those that contain  non-reifiable  arguments.  For
             example:
             public class ArrayBuilder {
               public static <T> void addToList (List<T> listArg, T... elements) {
                 for (T x : elements) {
                   listArg.add(x);
                 }
               }
             }
             The  compiler  generates the following warning for the definition
             of the method ArrayBuilder.addToList:
             warning: [varargs] Possible heap pollution from parameterized vararg type T
             When the compiler encounters a varargs method, it translates  the
             varargs  formal  parameter  into an array. However, the Java pro-
             gramming language does not  permit  the  creation  of  arrays  of
             parameterized  types.  In  the method ArrayBuilder.addToList, the
             compiler translates the varargs formal parameter T... elements to
             the  formal parameter T[] elements, an array. However, because of
             type erasure, the compiler converts the varargs formal  parameter
             to  Object[]  elements.  Consequently,  there is a possibility of
             heap pollution.

COMMAND LINE ARGUMENT FILES

       To shorten or simplify the javac command line, you can specify  one  or
       more  files  that  themselves  contain  arguments  to the javac command
       (except -J options). This enables you to create javac commands  of  any
       length on any operating system.
       An  argument file can include javac options and source filenames in any
       combination. The arguments within a file can be space-separated or new-
       line-separated.  If  a filename contains embedded spaces, put the whole
       filename in double quotes.
       Filenames within an argument file are relative to  the  current  direc-
       tory,  not  the  location  of  the argument file. Wildcards (*) are not
       allowed in these lists (such as for specifying *.java). Use of the  ‘@‘
       character  to  recursively  interpret  files  is  not supported. The -J
       options are not supported because they  are  passed  to  the  launcher,
       which does not support argument files.
       When  executing  javac, pass in the path and name of each argument file
       with the ‘@‘ leading  character.  When  javac  encounters  an  argument
       beginning  with the character `@‘, it expands the contents of that file
       into the argument list.
   Example - Single Arg File
       You could use a single argument file named "argfile" to hold all  javac
       arguments:

       % javac @argfile

       This  argument  file  could contain the contents of both files shown in
       the next example.
   Example - Two Arg Files
       You can create two argument files -- one for the javac options and  the
       other  for  the  source  filenames: (Notice the following lists have no
       line-continuation characters.)
       Create a file named "options" containing:

            -d classes
            -g
            -sourcepath /java/pubs/ws/1.3/src/share/classes

       Create a file named "classes" containing:

            MyClass1.java
            MyClass2.java
            MyClass3.java

       You would then run javac with:

         % javac @options @classes

   Example - Arg Files with Paths
       The argument files can have paths, but any filenames inside  the  files
       are relative to the current working directory (not path1 or path2):

       % javac @path1/options @path2/classes

ANNOTATION PROCESSING

       javac  provides  direct  support for annotation processing, superseding
       the need for the separate annotation processing tool, apt.
       The API for annotation  processors  is  defined  in  the  javax.annota-
       tion.processing and javax.lang.model packages and subpackages.
   Overview of annotation processing
       Unless  annotation  processing  is disabled with the -proc:none option,
       the compiler searches for any annotation processors that are available.
       The  search path can be specified with the -processorpath option; if it
       is not given, the user class path is used. Processors  are  located  by
       means  of  service  provider-configuration  files  named  META-INF/ser-
       vices/javax.annotation.processing.Processor on the  search  path.  Such
       files should contain the names of any annotation processors to be used,
       listed one per line. Alternatively, processors can be specified explic-
       itly, using the -processor option.
       After  scanning  the  source  files  and classes on the command line to
       determine what annotations are present, the compiler queries  the  pro-
       cessors  to  determine  what  annotations they process. When a match is
       found, the processor will be invoked. A processor may "claim" the anno-
       tations  it processes, in which case no further attempt is made to find
       any processors for those annotations. Once all  annotations  have  been
       claimed, the compiler does not look for additional processors.
       If any processors generate any new source files, another round of anno-
       tation processing will occur: any newly generated source files will  be
       scanned,  and  the  annotations  processed  as  before.  Any processors
       invoked on previous rounds will  also  be  invoked  on  all  subsequent
       rounds. This continues until no new source files are generated.
       After a round occurs where no new source files are generated, the anno-
       tation processors will be invoked one last time, to give them a  chance
       to  complete  any  work  they  may  need  to  do.  Finally,  unless the
       -proc:only option is used, the compiler will compile the  original  and
       all the generated source files.
   Implicitly loaded source files
       To  compile  a set of source files, the compiler may need to implicitly
       load additional source files. (See Searching For Types). Such files are
       currently  not  subject  to annotation processing. By default, the com-
       piler will give a warning if annotation processing has occurred and any
       implicitly  loaded  source files are compiled. See the -implicit option
       for ways to suppress the warning.
SEARCHING FOR TYPES

       When compiling a source file,  the  compiler  often  needs  information
       about  a type whose definition did not appear in the source files given
       on the command line. The compiler  needs  type  information  for  every
       class  or  interface used, extended, or implemented in the source file.
       This includes classes and interfaces not explicitly  mentioned  in  the
       source file but which provide information through inheritance.
       For  example,  when you subclass java.applet.Applet, you are also using
       Applet‘s   ancestor   classes:   java.awt.Panel,    java.awt.Container,
       java.awt.Component, and java.lang.Object.
       When the compiler needs type information, it looks for a source file or
       class file which defines the type.  The  compiler  searches  for  class
       files  first  in  the bootstrap and extension classes, then in the user
       class path (which by default is the current directory). The user  class
       path  is  defined  by  setting the CLASSPATH environment variable or by
       using the -classpath command line option. (For details, see Setting the
       Class Path).
       If  you set the -sourcepath option, the compiler searches the indicated
       path for source files; otherwise the compiler searches the  user  class
       path for both class files and source files.
       You  can  specify  different  bootstrap  or  extension classes with the
       -bootclasspath and  -extdirs  options;  see  Cross-Compilation  Options
       below.
       A  successful  type  search may produce a class file, a source file, or
       both. If both are found, you can use the -Xprefer  option  to  instruct
       the compiler which to use. If newer is given, the compiler will use the
       newer of the two files. If source is given,  it  will  use  the  source
       file. The default is newer.
       If  a  type  search  finds a source file for a required type, either by
       itself, or as a result of the setting for -Xprefer, the  compiler  will
       read  the  source file to get the information it needs. In addition, it
       will by default compile the source  file  as  well.  You  can  use  the
       -implicit  option  to  specify the behavior. If none is given, no class
       files will be generated for the source file. If class is  given,  class
       files will be generated for the source file.
       The  compiler may not discover the need for some type information until
       after annotation processing is complete. If  the  type  information  is
       found  in  a source file and no -implicit option is given, the compiler
       will give a warning that the file is being compiled without being  sub-
       ject  to  annotation processing. To disable the warning, either specify
       the file on the command line (so that it will be subject to  annotation
       processing) or use the -implicit option to specify whether or not class
       files should be generated for such source files.
PROGRAMMATIC INTERFACE

       javac supports the new Java Compiler API defined  by  the  classes  and
       interfaces in the javax.tools package.
   Example
       To  perform a compilation using arguments as you would give on the com-
       mand line, you can use the following:

       JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
       int rc = javac.run(null, null, null, args);

       This will write any diagnostics to  the  standard  output  stream,  and
       return  the  exit code that javac would give when invoked from the com-
       mand line.
       You can use other methods on the javax.tools.JavaCompiler interface  to
       handle  diagnostics,  control where files are read from and written to,
       and so on.
   Old Interface
       Note: This API is retained for backwards compatibility  only;  all  new
       code should use the Java Compiler API, described above.
       The  com.sun.tools.javac.Main  class  provides  two  static  methods to
       invoke the compiler from a program:

       public static int compile(String[] args);
       public static int compile(String[] args, PrintWriter out);

       The args parameter represents any of the command  line  arguments  that
       would  normally  be passed to the javac program and are outlined in the
       above Synopsis section.
       The out parameter indicates where the compiler‘s diagnostic  output  is
       directed.
       The return value is equivalent to the exit value from javac.
       Note  that  all other classes and methods found in a package whose name
       starts with com.sun.tools.javac (informally known  as  sub-packages  of
       com.sun.tools.javac) are strictly internal and subject to change at any
       time.
EXAMPLES

   Compiling a Simple Program
       One source file, Hello.java, defines a  class  called  greetings.Hello.
       The  greetings  directory  is the package directory both for the source
       file and the class file and is off the current directory.  This  allows
       us  to use the default user class path. It also makes it unnecessary to
       specify a separate destination directory with -d.

       % ls
       greetings/
       % ls greetings
       Hello.java
       % cat greetings/Hello.java
       package greetings;

       public class Hello {
           public static void main(String[] args) {
               for (int i=0; i < args.length; i++) {
                   System.out.println("Hello " + args[i]);
               }
           }
       }
       % javac greetings/Hello.java
       % ls greetings
       Hello.class   Hello.java
       % java greetings.Hello World Universe Everyone
       Hello World
       Hello Universe
       Hello Everyone

   Compiling Multiple Source Files
       This example compiles all the source files in the package greetings.

       % ls
       greetings/
       % ls greetings
       Aloha.java         GutenTag.java      Hello.java         Hi.java
       % javac greetings/*.java
       % ls greetings
       Aloha.class         GutenTag.class      Hello.class         Hi.class
       Aloha.java          GutenTag.java       Hello.java          Hi.java

   Specifying a User Class Path
       Having changed one of the source files  in  the  previous  example,  we
       recompile it:

       % pwd
       /examples
       % javac greetings/Hi.java

       Since  greetings.Hi  refers  to other classes in the greetings package,
       the compiler needs to find  these  other  classes.  The  example  above
       works,  because our default user class path happens to be the directory
       containing the package directory. But suppose we want to recompile this
       file  and not worry about which directory we‘re in? Then we need to add
       /examples to the user class path. We can do this by setting  CLASSPATH,
       but here we‘ll use the -classpath option.

       % javac -classpath /examples /examples/greetings/Hi.java

       If  we change greetings.Hi again, to use a banner utility, that utility
       also needs to be accessible through the user class path.

       % javac -classpath /examples:/lib/Banners.jar                    /examples/greetings/Hi.java

       To execute a class in greetings, we need access both to  greetings  and
       to the classes it uses.

       % java -classpath /examples:/lib/Banners.jar greetings.Hi

   Separating Source Files and Class Files
       It  often  makes sense to keep source files and class files in separate
       directories, especially on large projects. We use -d  to  indicate  the
       separate  class file destination. Since the source files are not in the
       user class path, we use -sourcepath to help the compiler find them.

       % ls
       classes/  lib/      src/
       % ls src
       farewells/
       % ls src/farewells
       Base.java      GoodBye.java
       % ls lib
       Banners.jar
       % ls classes
       % javac -sourcepath src -classpath classes:lib/Banners.jar                    src/farewells/GoodBye.java -d classes
       % ls classes
       farewells/
       % ls classes/farewells
       Base.class      GoodBye.class

       Note: The compiler compiled  src/farewells/Base.java,  even  though  we
       didn‘t specify it on the command line. To trace automatic compiles, use
       the -verbose option.
   Cross-Compilation Example
       The following example uses javac to compile code that will run on a 1.6
       VM.

       % javac -source 1.6 -target 1.6 -bootclasspath jdk1.6.0/lib/rt.jar                    -extdirs "" OldCode.java

       The  -source  1.6  option specifies that version 1.6 (or 6) of the Java
       programming language be used to compile OldCode.java. The option  -tar-
       get  1.6 option ensures that the generated class files will be compati-
       ble with 1.6 VMs. Note that in most cases, the  value  of  the  -target
       option  is  the  value  of the -source option; in this example, you can
       omit the -target option.
       You must specify the -bootclasspath option to specify the correct  ver-
       sion  of  the  bootstrap classes (the rt.jar library). If not, the com-
       piler generates a warning:

       % javac -source 1.6 OldCode.java
       warning: [options] bootstrap class path not set in conjunction with -source 1.6

       If you do not specify the correct version  of  bootstrap  classes,  the
       compiler  will use the old language rules (in this example, it will use
       version 1.6 of the Java programming language)  combined  with  the  new
       bootstrap  classes, which can result in class files that do not work on
       the older platform (in this case,  Java  SE  6)  because  reference  to
       non-existent methods can get included.
SEE ALSO

          o The javac Guide @
            http://docs.oracle.com/javase/7/docs/tech-
            notes/guides/javac/index.html

          o java(1) - the Java Application Launcher

          o jdb(1) - Java Application Debugger

          o javah(1) - C Header and Stub File Generator

          o javap(1) - Class File Disassembler

          o javadoc(1) - API Documentation Generator

          o jar(1) - JAR Archive Tool

          o The Java Extensions Framework @
            http://docs.oracle.com/javase/7/docs/technotes/guides/exten-
            sions/index.html

还是man厉害,不仅给出解释,还给出使用事例。

时间: 2024-10-26 20:13:31

学习 java命令的相关文章

Java命令学习系列(7):Javap(转)

原文出处: Hollis(@Hollis_Chuang) javap是jdk自带的一个工具,可以对代码反编译,也可以查看java编译器生成的字节码. 一般情况下,很少有人使用javap对class文件进行反编译,因为有很多成熟的反编译工具可以使用,比如jad.但是,javap还可以查看java编译器为我们生成的字节码.通过它,可以对照源代码和字节码,从而了解很多编译器内部的工作. 实例 javap命令分解一个class文件,它根据options来决定到底输出什么.如果没有使用options,那么

Java命令学习系列(一)——Jps

jps位于jdk的bin目录下,其作用是显示当前系统的java进程情况,及其id号. jps相当于Solaris进程工具ps.不象”pgrep java”或”ps -ef grep java”,jps并不使用应用程序名来查找JVM实例.因此,它查找所有的Java应用程序,包括即使没有使用java执行体的那种(例如,定制的启动 器).另外,jps仅查找当前用户的Java进程,而不是当前系统中的所有进程. 位置 我们知道,很多Java命令都在jdk的JAVA_HOME/bin/目录下面,jps也不例

Java学习之路(二) Java命令

1.java.exe:2.javac.exe:编译的Java程序编写的后缀为.java的文件,利用javac编译后会生成执行文件.class文件3.javaw.exe:运行Javac编译后生成的可执行文件.class文件,在执行图形界面的java程序运行java命令时,会出现一个console窗口并一直保持,并通过System.out将程序中的信息在console窗口内输出,avaw 大多用来运行GUI程序,运行javaw,JVM首先会调用控制台程序启动主程序,调用完主程序后就会隐藏控制台:4.

Java命令学习系列(零)——常见命令及Java Dump介绍

一.常用命令: 在JDK的bin目彔下,包含了java命令及其他实用工具. jps:查看本机的Java中进程信息. jstack:打印线程的栈信息,制作线程Dump. jmap:打印内存映射,制作堆Dump. jstat:性能监控工具. jhat:内存分析工具. jconsole:简易的可视化控制台. jvisualvm:功能强大的控制台. 二.认识Java Dump: 什么是Java Dump? Java虚拟机的运行时快照.将Java虚拟机运行时的状态和信息保存到文件. 线程Dump,包含所有

学习java之前

声明:本栏目所使用的素材都是凯哥学堂VIP学员所写,学员有权匿名,对文章有最终解释权:凯哥学堂旨在促进VIP学员互相学习的基础上公开笔记. 学习java之前 2.1认识JDK 工具包: 编译和运行其使用的是JDK里面的编译和运行,首先得下载JDK; 1.JDK的安装: JDK的官网:(http://www.oracle.com) 找到处按以下步骤: 2.安装JDK : 先双击一下jdk-8u144-windows-x64.exe然后进入安装: 然后在你写的路径下生成了文件 就是JDK的目录的位置

通过Tomcat的Http11NioProtocol源码学习Java NIO设计

Tomcat的Http11NioProtocol协议使用Java NIO技术实现高性能Web服务器.本文通过分析Http11NioProtocol源码来学习Java NIO的使用.从中可以了解到阻塞IO和非阻塞IO的配合,NIO的读写操作以及Selector.wakeup的使用. 1. 初始化阶段 Java NIO服务器端实现的第一步是开启一个新的ServerSocketChannel对象.Http11NioProtocol的实现也不例外, 在NioEndPoint类的init方法可以看到这段代

java 命令行 编译 运行程序

学习java使用IDE前最好先用用命令行的javac.java来跑一跑简单的程序,这样能够熟悉一下包管理对.class文件路径的影响. 我们先写一段简单的代码: package com.csdn.lkasdolka; public class test_1{ public static void main(String[] args){ for(int i = 0; i < 10; ++i ){ System.out.println(i); } } } 写好后保存为test_1.java,win

学习Java 的第一篇文章

第一章   Java基础 1.学习方法: 01.找一本好书 初始阶段不适合,可以放到第二个阶段,看到知识点时,要进行验证 02.查看帮助文档和搜索引擎的使用 借助网络上的Blog文章 03.不要急功近利 不要抱着速成的想法,否则必然走弯路     学习编程不是一蹴而就的事情     付出的成本高,才能有一个高薪的收入 04.不要浮躁 不要什么都学,只学有用的 浮躁的程度和技术水平成反比的     走自己的路,让别人去浮躁去吧! 每天问问自己,我是不是开始浮躁了,不能人云亦云. 05.学习语言基础

java 命令行 编译 执行程序

学习java使用IDE前最好先用用命令行的javac.java来跑一跑简单的程序,这样可以熟悉一下包管理对.class文件路径的影响. 我们先写一段简单的代码: package com.csdn.lkasdolka; public class test_1{ public static void main(String[] args){ for(int i = 0; i < 10; ++i ){ System.out.println(i); } } } 写好后保存为test_1.java,win