为什么加上@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://blog.csdn.net/shan9liang/article/details/29625683