1.注解的定义,目前注解包括三种标准注解(@Override, @Deprecated, @SuppressWarnings) 和四种元注解(@Target, @Retention, @Documented, @Inherited)
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Constraints {
boolean primaryKey() default false;
boolean allowNull() default true;
boolean unique() default false;
}
看上去很像一个空的接口,其中@Target表示该注解可用于什么地方,可选的ElementType参数包括:
CONSTRUCTOR | 构造器 |
FIELD | 域(包括emun) |
LOCAL_VARIABLE | 局部变量 |
METHOD | 方法 |
PACKAGE | 包 |
PARAMETER | 参数 |
TYPE | 类,接口,注解,enum |
@Retention表示需要在什么级别保存该注解信息,可选的RetentionPolicy参数包括:
SOURCE | 注解将被编译器丢失 |
CLASS | 注解在class中可用,但被VM丢失 |
RUNTIME | VM将在运行期也保留注解,因此可以通过反射读取注解的信息 |
2. “boolean primaryKey() default false”称为注解元素,可用的类型有
所有基本类型(boolean, char, byte, short, int, long, float, double ) |
String |
Class |
enum |
Annotation |
以上类型的数组 |
3. 注解的小应用
1)定义一个用于测试的注解
package com.desmond.test.annotation.vo;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Test {
}
2)测试类
package com.desmond.test.annotation.test;
import com.desmond.test.annotation.vo.Test;
public class TestAtUnit {
@Test
public void test() {
add(2, 3);
substract(3, 9);
multiplication(4, 8);
division(3, 4);
}
public void add(double x, double y) {
System.out.println(x + " + " + y + "=" + (x + y));
}
private void substract(double x, double y) {
System.out.println(x + " - " + y + "=" + (x - y));
}
protected void multiplication(double x, double y) {
System.out.println(x + " * " + y + "=" + (x * y));
}
void division(double x, double y) {
System.out.println(x + " / " + y + "=" + (x / y));
}
}
3)运行类
package com.desmond.test.annotation.test;
import com.desmond.test.annotation.vo.Test;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class AtUnitTest {
/**
* @param args
*/
public static void main(String[] args) {
Class<?> cl = TestAtUnit.class;
Method[] methods = cl.getDeclaredMethods();
for(Method md : methods) {
Annotation[] annos = md.getAnnotations();
for(Annotation ann : annos) {
if(ann instanceof Test) {
try {
md.invoke(new TestAtUnit(), null);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
4)Output:
2.0 + 3.0=5.0
3.0 - 9.0=-6.0
4.0 * 8.0=32.0
3.0 / 4.0=0.75