Annotation – @Deprecated @Override @SuppressWarnings

JDK5.0 引入了一种新的元语言工具,叫“annotation”。 Annotation 提供的信息不是程序的一部分,例如,代码片断的作者,或者告诉编译器忽略特定的错误等。Annotation不会对程序的运行产生任何影响。

Annotation的形式为:@annotation。它可以被应用到类,属性,方法等的声明处。Annotation位于他们之前,并且(通常)独立一行。它还可以带有参数,例如:
    @Author("MyName")
    class myClass {}
或者
    @SuppressWarnings("unchecked")
    void MyMethod() {}

自定义annotation属于高级用法,不属于本文讨论范畴。但是有三个内置的annotation你必须知道(如果你是Java程序员的话),他们是@Deprecated,@Override和@SuppressWarnings。以下列举他们对于方法的应用。
import java.util.List;

class Food {}
class Hay extends Food {}
class Animal {
Food getPreferredFood() {
return null;
}
/**
* @deprecated document why the method was deprecated
*/
@Deprecated
static void deprecatedMethod() { }
}
class Horse extends Animal {
Horse() {
return;
}
@Override
Hay getPreferredFood() {
return new Hay();
}
@SuppressWarnings("deprecation")
void useDeprecatedMethod() {
Animal.deprecateMethod(); //deprecation warning - suppressed
}
}
@Deprecated

@Deprecated annotation 表示被标志的方法不应该被继续使用了,如果程序使用了deprecated的类,变量或方法,编译器将会给出警告。如果一个元素被deprecate了,那么应该如上例所示在上面的注释文档中添加deprecated的标记并给出原因。注意,文档中标记的首字母是小写d,annotation中的首字母是大写D。一般来说,你应该避免使用deprecated的方法,可以参阅相关文档了解替代方法。

@Override

@Override annotation是为了告诉编译器,该元素会override父类的这个元素。在上例中,override annotation表示Horse中的getPreferredFood方法将会override 父类Animal中的getPreferredFood方法。如果这步失败,编译器会报错。

尽管Override的时候并不是必须使用这个annotation,使用它还是可以使程序逻辑更明了化,特别是当子类方法的返回值继承自父类方法的返回值。如在上例中,子类的getPreferredFood方法返回Hey的实例,父类的getPreferredFood方法返回Food的实例,其中Hey继承Food。更多信息见Overriding and Hiding Methods

@SuppressWarnings

@SuppressWarnings告诉编译器,此处不要报错。在上例中,useDeprecatedMethod方法调用了Animal类中的deprecated方法,通常编译器会给出警告,但是此处,被suprress了。

每一个编译器警告属于一个类别,Java语言规范中列出了两类:“deprecation” 和“unchecked”。如果要suppress这两类警告,使用如下方式:
    @SuppressWarnings ( {"unchecked", "deprecation"} )
参见编译器文档了解警告的类别。

对于annotation更高级的用法是写一段程序不仅可以读java代码,并且可以处理annotations。为了达到这个目标,5.0JDK中包含了一个处理annotation的工具,称为apt。下一个版本JDK(代号Mustang)的apt将成为Java编译器的一个标准部分。更多信息,可以参见Getting Started with the Annotation Processing Tool。关于正在实现的Mustang感兴趣,可以参见Language Model APIJSR 269: Pluggable Annotation Processing API


How to use @SuppressWarnings

Sometimes you will got the warning in Java when you are using the eclipse. And this is kind of annoying. Now you can use this to eliminate it:

@SuppressWarnings(option)

This can be categorized into two categories:

  • Put this notation right before the code with warning:
    • @SuppressWarnings("unused") String unused = "never";
  • Put this notation right before the class declaration
    • @SuppressWarnings("deprecation")
    • class DeprecationExample{ ... }

I think the warning options in red should be categoried into category 2.

You can simply try this out!

 

Warning options
-warn:
allDeprecation
allJavadoc
assertIdentifier
boxing
charConcat
conditionAssign
constructorName
dep-ann
deprecation
discouraged
emptyBlock
enumSwitch
fallthrough
fieldHiding
finalBound
finally
forbidden
hiding
incomplete-switch
indirectStatic
intfAnnotation
intfNonInherited
javadoc
localHiding
maskedCatchBlocks
nls
noEffectAssign
null
over-ann
paramAssign
pkgDefaultMethod
raw
semicolon
serial
specialParamHiding
static-access
staticReceiver
suppress
synthetic-access
syntheticAccess
tasks(<task1>|...|<taskN>)
typeHiding
unchecked
unnecessaryElse
unqualified-field-access
unqualifiedField
unused
unusedArgument
unusedImport
unusedLabel
unusedLocal
unusedPrivate
unusedThrown
uselessTypeCheck
varargsCast
warningToken
Set warning level.
e.g. -warn:unusedLocal,deprecation

In red are the default settings.

-warn:none disable all warnings -warn:<warnings separated by ,> enable exactly the listed warnings -warn:+<warnings separated by ,> enable additional warnings -warn:-<warnings separated by ,> disable specific warnings
allDeprecation deprecation even inside deprecated code
allJavadoc invalid or missing javadoc
assertIdentifier occurrence of assert used as identifier
boxing autoboxing conversion
charConcat when a char array is used in a string concatenation without being converted explicitly to a string
conditionAssign possible accidental boolean assignment
constructorName method with constructor name
dep-ann missing @Deprecated annotation
deprecation usage of deprecated type or member outside deprecated code
discouraged use of types matching a discouraged access rule
emptyBlock undocumented empty block
enumSwitch,
incomplete-switch
incomplete enum switch
fallthrough possible fall-through case
fieldHiding field hiding another variable
finalBound type parameter with final bound
finally finally block not completing normally
forbidden use of types matching a forbidden access rule
hiding macro for fieldHiding, localHiding, typeHiding and maskedCatchBlock
indirectStatic indirect reference to static member
intfAnnotation annotation type used as super interface
intfNonInherited interface non-inherited method compatibility
javadoc invalid javadoc
localHiding local variable hiding another variable
maskedCatchBlocks hidden catch block
nls non-nls string literals (lacking of tags //$NON-NLS-<n>)
noEffectAssign assignment with no effect
null missing or redundant null check
over-ann missing @Override annotation
paramAssign assignment to a parameter
pkgDefaultMethod attempt to override package-default method
raw usage a of raw type (instead of a parametrized type)
semicolon unnecessary semicolon or empty statement
serial missing serialVersionUID
specialParamHiding constructor or setter parameter hiding another field
static-access macro for indirectStatic and staticReceiver
staticReceiver if a non static receiver is used to get a static field or call a static method
suppress enable @SuppressWarnings
syntheticAccess,
synthetic-access
when performing synthetic access for innerclass
tasks enable support for tasks tags in source code
typeHiding type parameter hiding another type
unchecked unchecked type operation
unnecessaryElse unnecessary else clause
unqualified-field-access,
unqualifiedField
unqualified reference to field
unused macro for unusedArgument, unusedImport, unusedLabel, unusedLocal, unusedPrivate and unusedThrown
unusedArgument unused method argument
unusedImport unused import reference
unusedLabel unused label
unusedLocal unused local variable
unusedPrivate unused private member declaration
unusedThrown unused declared thrown exception
uselessTypeCheck unnecessary cast/instanceof operation
varargsCast varargs argument need explicit cast
warningToken unhandled warning token in @SuppressWarnings

 

Refer from : Eclipse Help Doc


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值