为什么加上@Override,当前的方法就定义将覆盖超类中的方法,假设不覆盖就编译报错?
为什么使用加上@Deprecated的。编译器将发出警告,这是弃用的代码?
为什么加上@SuppressWarnings,编译器就不再发出警告信息?
package com.jialin.test.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @Author : JiaLin
* @Group : TGB
* @Date : 2014/6/9
* @Description :
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyDeprecated {
public String description() default "Warning:This method is Deprecated!";
}
|
@Target |
表示该注解能够用于什么地方。可能的ElementType參数有: CONSTRUCTOR:构造器的声明 FIELD:域声明(包含enum实例) LOCAL_VARIABLE:局部变量声明 METHOD:方法声明 PACKAGE:包声明 PARAMETER:參数声明 TYPE:类、接口(包含注解类型)或enum声明 |
|
@Retention |
表示须要在什么级别保存该注解信息。可选的RetentionPolicy參数包含: SOURCE:注解将被编译器丢弃 CLASS:注解在class文件里可用,但会被VM丢弃 RUNTIME:VM将在执行期间保留注解,因此能够通过反射机制读取注解的信息。 |
|
@Document |
将注解包括在Javadoc中 |
|
@Inherited |
同意子类继承父类中的注解 |
package com.jialin.test.annotation;
import java.lang.reflect.Method;
/**
* @Author : JiaLin
* @Group : TGB
* @Date : 2014/6/9
* @Description :
*/
public class MyClass {
@MyDeprecated
public String sayHelloWorld()
{
return "Hello,World!";
}
public String sayHelloJiaLin()
{
return "Hello,Jialin!";
}
public static void main(String[] args) {
testMyDeclared(MyClass.class);
}
public static void testMyDeclared(Class<?> myClass) {
for (Method method : myClass.getDeclaredMethods()) {
MyDeprecated myDeprecated = method.getAnnotation(MyDeprecated.class);
if (myDeprecated != null) {
System.out.println(myDeprecated.description()+method.getName());
}
}
}
}
原文:http://www.cnblogs.com/yutingliuyl/p/6917263.html