在OptionName类中的枚举定义如下:

XLINT("-Xlint"),
XLINT_CUSTOM("-Xlint:"),

-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.

其中的name可以使用如下的一些值:

/**
* Categories of warnings that can be generated by the compiler.
*/
public enum LintCategory {
        /**
         * Warn about use of unnecessary casts.
         */
        CAST("cast"),

        /**
         * Warn about issues related to classfile contents
         */
        CLASSFILE("classfile"),

        /**
         * Warn about use of deprecated items.
         */
        DEPRECATION("deprecation"),

        /**
         * Warn about items which are documented with an {@code @deprecated} JavaDoc
         * comment, but which do not have {@code @Deprecated} annotation.
         */
        DEP_ANN("dep-ann"),

        /**
         * Warn about division by constant integer 0.
         */
        DIVZERO("divzero"),

        /**
         * Warn about empty statement after if.
         */
        EMPTY("empty"),

        /**
         * Warn about falling through from one case of a switch statement to the next.
         */
        FALLTHROUGH("fallthrough"),

        /**
         * Warn about finally clauses that do not terminate normally.
         */
        FINALLY("finally"),

        /**
         * Warn about issues relating to use of command line options
         */
        OPTIONS("options"),

        /**
         * Warn about issues regarding method overrides.
         */
        OVERRIDES("overrides"),

        /**
         * Warn about invalid path elements on the command line.
         * Such warnings cannot be suppressed with the SuppressWarnings
         * annotation.
         */
        PATH("path"),

        /**
         * Warn about issues regarding annotation processing.
         */
        PROCESSING("processing"),

        /**
         * Warn about unchecked operations on raw types.
         */
        RAW("rawtypes"),

        /**
         * Warn about Serializable classes that do not provide a serial version ID.
         */
        SERIAL("serial"),

        /**
         * Warn about issues relating to use of statics
         */
        STATIC("static"),

        /**
         * Warn about proprietary API that may be removed in a future release.
         */
        SUNAPI("sunapi", true),

        /**
         * Warn about issues relating to use of try blocks (i.e. try-with-resources)
         */
        TRY("try"),

        /**
         * Warn about unchecked operations on raw types.
         */
        UNCHECKED("unchecked"),

        /**
         * Warn about potentially unsafe vararg methods
         */
        VARARGS("varargs");

        LintCategory(String option) {
            this(option, false);
        }

        LintCategory(String option, boolean hidden) {
            this.option = option;
            this.hidden = hidden;
            map.put(option, this);
        }

        static LintCategory get(String option) {
            return map.get(option);
        }

        public final String option;
        public final boolean hidden;
};

在javac中Lint类主要来实现-Xlint命令的功能,将警告分为如下几类:

1、cast Warn about unnecessary and redundant casts. For example:

String s = (String)"Hello!"

2、classfileWarn about issues related to classfile contents.

3、deprecationWarn about use of deprecated items. For example:

java.util.Date myDate = new java.util.Date();
int currentDay = myDate.getDay();

注解的@Deprecated,它对编译器说明某个方法已经不建议使用,如果有人试图使用或重新定义该方法,必须提出警示讯息。

4、The method java.util.Date.getDay has been deprecated since JDK 1.1.dep-annWarn 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() { }

注释中的@deprecated用于在用Javadoc工具生成文档的时候,标注此类/接口、方法、字段已经被废止。

5、divzeroWarn about division by constant integer 0. For example:

int divideByZero = 42 / 0;

6、emptyWarn about empty statements after if statements. For example:

class E {
   void m() {
      if (true) ;
   }
}

7、fallthroughCheck 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.

8、finallyWarn 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 example. 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 executed, even though control has already been transferred outside the method.optionsWarn about issues relating to the use of command line options. See Cross-Compilation Example for an example of this kind of warning.

9、overridesWarn about issues regarding method overrides. For example, consider 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 ClassWithOverridingMethod overrides varargsMethod(String...) in ClassWithVarargsMethod; overriding method is missing '...'

When the compiler encounters a varargs method, it translates the varargs formal parameter into an array. In the method ClassWithVarargsMethod.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 ClassWithOverridingMethod.varargsMethod. Consequently, this example compiles.

10、pathWarn 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

  


11、processingWarn about issues regarding annotation processing. The compiler generates this warning if you have a class that has an annotation, and you use an annotation processor that cannot handle that type of exception. For example, the following is a simple annotation 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 following warning:

warning: [processing] No processor claimed any of these annotations: Anno

To resolve this issue, you can rename the annotation defined and used in the class AnnosWithoutProcessors from Anno to NotAnno.rawtypesWarn about unchecked operations on raw types. The following statement generates a rawtypes warning:

void countElements(List l) { ... }

  

12、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.

13、serialWarn 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 definition 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 Serialization 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.

14、staticWarn 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 follows:

XLintStatic.m1();

  

Alternatively, you can remove the static keyword from the declaration of the method m1.

15、tryWarn about issues relating to use of try blocks, including try-with-resources statements. For example, a warning is generated for the following statement because the resource ac declared in the try statement is not used:

try (BufferedReader br =  new BufferedReader(new FileReader("path"))) {
           // do nothing
}

16、uncheckedGive more detail for unchecked conversion warnings that are mandated by the Java Language Specification. For example:

List lx = new ArrayList<Number>();
List<String> ls = lx;

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 determine 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>. However, 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.

17、varargsWarn 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 programming 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.  

汇总一下:

public class Test1 implements Serializable {
    public static <T> int addToList (List<T> listArg, T... elements)  {
        // cast
        String s = (String)"Hello!";

        // deprecation
        java.util.Date myDate = new java.util.Date();
        int currentDay = myDate.getDay();

        // dep-ann
        deprecatedMethood();

        // divzero
        int divideByZero = 42 / 0;

        // empty
        if (true) ;

        // fallthrough
        int x = 2;
        switch (x) {
            case 1:
                System.out.println("1");       //  No break statement here.
            case 2:
                System.out.println("2");
        }

        // override
        class ClassWithVarargsMethod {
            void varargsMethod(String... s) {

            }
        }
        class ClassWithOverridingMethod extends ClassWithVarargsMethod {
            @Override
            void varargsMethod(String[] s) {

            }
        }

        // rawtypes
        List l;

        // static
        m1();

        // try
        try (BufferedReader br =  new BufferedReader(new FileReader("test.txt"))) {
           // do nothing
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // unchecked
        List lx = new ArrayList<Number>();
        List<String> ls = lx;

        // varargs
        for (T xd : elements) {
            listArg.add(xd);
        }

        // finally
        try {
            throw new NullPointerException();
        } catch (NullPointerException e) {
            System.err.println("Caught NullPointerException.");
            return 1;
        } finally {
            return 0;
        }

    }

    /**
     * @deprecated As of Java SE 7, replaced by {@link #newMethod()}
     */
    public static void deprecatedMethood() { }
    public static void newMethod() { }

    static void m1() {

    }
}

通过javac编译器运行后的结果如下:

H:\program workspace\project\Compiler_javac\test\com\test15\Test1.java:11: 警告: [unchecked] 参数化 vararg 类型T的堆可能已受污染
    public static <T> int addToList (List<T> listArg, T... elements)  {
                                             ^
  其中, T是类型变量:
    T扩展已在方法 <T>addToList(List<T>,T...)中声明的Object
H:\program workspace\project\Compiler_javac\test\com\test15\Test1.java:17: 警告: [deprecation] Date中的getDay()已过时
        int currentDay = myDate.getDay();
                               ^
H:\program workspace\project\Compiler_javac\test\com\test15\Test1.java:23: 警告: [divzero] 除数为零
        int divideByZero = 42 / 0;
                                ^
H:\program workspace\project\Compiler_javac\test\com\test15\Test1.java:26: 警告: [empty] if 之后没有语句
        if (true) ;
                  ^
H:\program workspace\project\Compiler_javac\test\com\test15\Test1.java:45: 警告: ClassWithOverridingMethod中的varargsMethod(String[])覆盖了ClassWithVarargsMethod中的varargsMethod(String...); 覆盖的方法缺少 '...'
            void varargsMethod(String[] s) {
                 ^
H:\program workspace\project\Compiler_javac\test\com\test15\Test1.java:51: 警告: [rawtypes] 找到原始类型: List
        List l;
        ^
  缺少泛型类List<E>的类型参数
  其中, E是类型变量:
    E扩展已在接口 List中声明的Object
H:\program workspace\project\Compiler_javac\test\com\test15\Test1.java:66: 警告: [rawtypes] 找到原始类型: List
        List lx = new ArrayList<Number>();
        ^
  缺少泛型类List<E>的类型参数
  其中, E是类型变量:
    E扩展已在接口 List中声明的Object
H:\program workspace\project\Compiler_javac\test\com\test15\Test1.java:66: 警告: 新表达式中存在冗余类型参数 (改用 diamond 运算符)。
        List lx = new ArrayList<Number>();
                               ^
  显式: ArrayList<Number>
  推断: ArrayList<Object>
H:\program workspace\project\Compiler_javac\test\com\test15\Test1.java:67: 警告: [unchecked] 未经检查的转换
        List<String> ls = lx;
                          ^
  需要: List<String>
  找到:    List
H:\program workspace\project\Compiler_javac\test\com\test15\Test1.java:90: 警告: [dep-ann] 未使用 @Deprecated 对已过时的项目进行注释
    public static void deprecatedMethood() { }
                       ^
H:\program workspace\project\Compiler_javac\test\com\test15\Test1.java:10: 警告: [serial] 可序列化类Test1没有 serialVersionUID 的定义
public class Test1 implements Serializable {
       ^
H:\program workspace\project\Compiler_javac\test\com\test15\Test1.java:13: 警告: [cast] 出现冗余的到String的转换
        String s = (String)"Hello!";
                   ^
H:\program workspace\project\Compiler_javac\test\com\test15\Test1.java:33: 警告: [fallthrough] 可能无法实现 case
            case 2:
            ^
H:\program workspace\project\Compiler_javac\test\com\test15\Test1.java:57: 警告: [try] 不能在相应的 try 语句的正文中引用可自动结束的资源br
        try (BufferedReader br =  new BufferedReader(new FileReader("test.txt"))) {
                            ^
H:\program workspace\project\Compiler_javac\test\com\test15\Test1.java:82: 警告: [finally] finally 子句无法正常完成
        }
        ^

  

有必要了解下@SuppresssWarnings注解,功能是忽略警告。可以标注在类、字段、方法、参数、构造方法,以及局部变量上。告诉编译器忽略指定的警告,不用在编译完成后出现警告信息。

例如:

(1)@SuppressWarnings("unchecked")

告诉编译器忽略 unchecked 警告信息,如使用List,ArrayList等未进行参数化产生的警告信息。

(2)@SuppressWarnings("deprecation")

如果使用了使用@Deprecated注释的方法,编译器将出现警告信息。 使用这个注释将警告信息去掉。

(3)@SuppressWarnings({"unchecked", "deprecation"})

告诉编译器同时忽略unchecked和deprecation的警告信息。

Javac的命令(-Xlint)的更多相关文章

  1. Javac的命令

    关于命令,还可以查看<Java 7程序设计>一书后面的附录A As per javac source docs, there are 4 kinds of options: standar ...

  2. javac的命令(-Xbootclasspath、-classpath与-sourcepath等)

    当编译源文件时,编译器常常需要识别出类型的有关信息.对于源文件中使用.扩展或实现的每个类或接口,编译器都需要其类型信息.这包括在源文件中没有明确提及.但通过继承提供信息的类和接口. 例如,当扩展 ja ...

  3. 将Java和Javac的命令在控制台的输出重定向到txt文件

    当我们在Windows控制台窗口执行程序时,输入如下命令: demo.exe > out.txt 就可以把demo程序的输出重定向到out.txt文件里面. 但是这种方法对于java和javac ...

  4. java-关于java_home配置,classpath配置和javac,java命令,javac编译器,和java虚拟机之间的关系

    在每个人学习java的第一步,都是安装jdk ,jre,配置java_home,classpath,path. 为什么要做这些?在阅读java-core的时候,看到了原理,p141. 一 关于类的共享 ...

  5. Javac的命令(注解相关)

    1.-Akey[=value] Options to pass to annotation processors. These are not interpreted by javac directl ...

  6. 在CMD窗口中使用javac和java命令进行编译和执行带有包名的具有继承关系的类

    一.背景 最近在使用记事本编写带有包名并且有继承关系的java代码并运行时发现出现了很多错误,经过努力一一被解决,今天我们来看一下会遇见哪些问题,并给出解决办法. 二.测试过程 1.父类代码 pack ...

  7. 命令查看java的class字节码文件、verbose、synchronize、javac、javap

    查看Java字节码 1 javac –verbose查看运行类是加载了那些jar文件 HelloWorld演示: public class Test { public static void main ...

  8. javac不是内部或外部命令在win10上的解决方案

    Path环境变量能够让你在任何路径都能使用命令,可能你百度谷歌了各种方案都无法解决javac无法使用的问题,那么你可以试试如下解决方案: 首先博主配置了JAVA_HOME 参数为 C:\Program ...

  9. 第一章-Javac编译器介绍

    1.Javac概述 编译器可以将编程语言的代码转换为其他形式,如Javac,将Java语言转换为虚拟机能够识别的.class文件形式.而这种将java源代码(以.java做为文件存储格式)转换为cla ...

随机推荐

  1. REQUEST的TRACE文件

    --REQUEST的TRACE文件 SELECT    'Trace Name: '       || DEST.VALUE       || '/'       || LOWER (DBNM.VAL ...

  2. 原创:MVC 5 实例教程(MvcMovieStore 新概念版:mvc5.0,EF6.01) - 3、创建项目

    说明:MvcMovieStore项目已经发布上线,想了解最新版本功能请登录 MVC 影视(MvcMovie.cn) 进行查阅.如需转载,请注明出处:http://www.cnblogs.com/Dod ...

  3. 解决vs2017调试出现脚本错误(/Community/Common7/IDE/PrivateAssemblies/plugin.vs.js) 方法

    原文地址:http://bkcoding.cn/post_1204.html 新装的vs2017编译时出现当前页面脚本错误 url:/Community/Common7/IDE/PrivateAsse ...

  4. Devexpress Tab Control 文档

    https://documentation.devexpress.com/WPF/8078/Controls-and-Libraries/Layout-Management/Tab-Control/P ...

  5. WPF TriggerAction弹出子窗体 TargetedTrigger、TargetedTriggerAction用法

    namespace TriggerAction { public class OpenWindowAction : TriggerAction<DependencyObject> { pu ...

  6. Fiddler关闭后打不开网页

    今天项目系统测试的时候,CS客户端的Restful请求都失败,但是实际上的服务是正常开启的,马上通过cmd指令ping了一下服务,正常:再用telnet试了一下端口,也是正常.不过随后发现在这台电脑上 ...

  7. [Cocos2d-x for WP8学习笔记] 获取系统字体

    在Cocos2d-x for WP8较新的版本中,获取字体这一块,在wp8下默认返回了null,只能内嵌字体文件解决. 其实可以通过下面的方法获取系统的字体文件 CCFreeTypeFont::loa ...

  8. ES6学习之let声明变量的学习

    1.let和var类似, (1)let与var不同的点:let没有预编译,变量提升这个过程,let声明的变量只能在当前作用域内访问到(一个{}可以看做是一个作用域),在全局var声明的变量属于wind ...

  9. 内置函数——sorted

    对List.Dict进行排序,Python提供了两个方法对给定的List L进行排序,方法1.用List的成员函数sort进行排序,在本地进行排序,不返回副本方法2.用built-in函数sorted ...

  10. (转)科普:SATA、PCIe、AHCI、NVMe

    原文链接:https://forum.51nb.com/thread-1670848-1-1.html IT 界总喜欢发明新名词.而且同一个东西,可能有几个不同的名字.同一个名字,又可能指不同的东西. ...