java SE5 内置了三种,定义在java.lang中的注解
1.@Override,表示当前的方法定义将覆盖超类中的方法。如果你不小心拼写错误,或者方法签名对不上被覆盖的方法,编译器就会发出错误提示。
2.@Deprecated,如果程序员使用了注解为它的元素,那么编译器会发出警告信息。
3.@SuppressWarnings,关闭不当的编译器警告信息,在Java SE5之前的版本中,也可以使用该注解,不过会被忽略不起作用。
四种元注解:
1.@Target:表示该注解可以用于什么地方。可能的ElementType参数包括:
CONSTRUCTOR:构造器的声明
FIELD:域声明(包括enum实例)
LOCAL_VARIABLE:局部变量声明
METHOD:方法声明
PACKAGE:包声明
PARAMETER:参数声明
TYPE:类、接口(包括注解类型)或enum声明
2.@Retention:表示需要什么级别保存该注解信息。可选的RetentionPolicy参数包括:
SOURCE:注解将被编译器丢弃。
CLASS:注解在class文件中可用,但会被VM丢弃。
RUNTIME:VM将在运行期也保留注解,因此可以通过反射机制读取注解的信息。
3.Documented:将此注解包含在Javadoc中
4.Inherited:允许子类继承父类中的注解
简单的例子:
package anno;
import java.lang.annotation.*;
/**
* 元注解:@Target用来定义你的注解将应用于什么地方(例如一个方法或者一个域)
* @Retention 定义该注解在哪一个级别可用,在源代码中(SOURCE)、类文件中(CLASS)、或者运行时(RUNTIME)
* @author Administrator
*
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface UseCase {
public int id();
public String description() default "no description";
}
package anno;
import java.util.List;
public class PasswordUtils {
@UseCase(id=47,description="Passwords must contain at least one numeric")
public boolean validatePassword(String password) {
return (password.matches("\\w*\\d\\w*"));
}
@UseCase(id=48)
public String encryptPassword(String password) {
return new StringBuilder(password).reverse().toString();
}
@UseCase(id=49,description="New passwords can't equal previously used ones")
public boolean checkForNewPassword(List<String> prevPasswords,String password) {
return !prevPasswords.contains(password);
}
}
package anno;
import java.lang.reflect.*;
import java.util.*;
/**
* 注解处理器
* @author Administrator
*
*/
public class UseCaseTracker {
public static void trackUseCases(List<Integer> useCases,Class<?> cl) {
for(Method m:cl.getDeclaredMethods()) {
UseCase uc = m.getAnnotation(UseCase.class);
if(uc!=null) {
System.out.println("Found Use Case:"+uc.id()+
" "+uc.description());
useCases.remove(new Integer(uc.id()));
}
}
for(int i:useCases) {
System.out.println("Warning:Missing use case-"+i);
}
}
public static void main(String[] args) {
List<Integer> useCases = new ArrayList<Integer>();
Collections.addAll(useCases,47,48,49,50);
trackUseCases(useCases, PasswordUtils.class);
}
}
//输出结果:
//Found Use Case:49 New passwords can't equal previously used ones
//Found Use Case:47 Passwords must contain at least one numeric
//Found Use Case:48 no description
//Warning:Missing use case-50
注解元素:
1.所有基本类型(int,float,boolean等)
2.String
3.Class
4.enum
5.Annotation
6.以上类型的数组
package anno;
import java.lang.annotation.*;
/**
* 元素必须要么具有默认值,要么在使用注解时提供元素的值。其次,对于非基本类型的元素,无论是在源代码中声明
* 时,或是在注解接口中定义默认值时,都不能以null作为其值。只好自己定义一些特殊的值,例如空字符串或负数,以此
* 表示某个元素不存则
* @author Administrator
*
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SimulatingNull {
public int id() default -1;
public String description() default "";
}