1 注解
1.1 元注解
@Target注解的作用是:描述注解的使用范围(即:被修饰的注解可以用在什么地方)
注解可以用于修饰 packages、types(类、接口、枚举、注解类)、类成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch参数),在定义注解类时使用了@Target 能够更加清晰的知道它能够被用来修饰哪些对象,它的取值范围定义在ElementType 枚举中
public enum ElementType {
TYPE, // 类、接口、枚举类
FIELD, // 成员变量(包括:枚举常量)
METHOD, // 成员方法
PARAMETER, // 方法参数
CONSTRUCTOR, // 构造方法
LOCAL_VARIABLE, // 局部变量
ANNOTATION_TYPE, // 注解类
PACKAGE, // 可用于修饰:包
TYPE_PARAMETER, // 类型参数,JDK 1.8 新增
TYPE_USE // 使用类型的任何地方,JDK 1.8 新增
}
@Retention
Reteniton注解的作用是:描述注解保留的时间范围(即:被描述的注解在它所修饰的类中可以被保留到何时)
Reteniton注解用来限定那些被它所注解的注解类在注解到其他类上以后,可被保留到何时,一共有三种策略,定义在RetentionPolicy枚举中
public enum RetentionPolicy {
SOURCE, // 源文件保留
CLASS, // 编译期保留,默认值
RUNTIME // 运行期保留,可通过反射去获取注解信息
}
@Documented
Documented注解的作用是:描述在使用 javadoc 工具为类生成帮助文档时是否要保留其注解信息。
@Inherited
Inherited注解的作用是:使被它修饰的注解具有继承性(如果某个类使用了被@Inherited修饰的注解,则其子类将自动具有该注解)
2 反射(Reflction)
访问私有的属性和方法需要关闭安全检测
2 通过反射获取泛型
3 反射获取注解
package annocation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@UserClass(db = "mydb")
public class User {
@UserFiled(column = "id",type = "varchar",length = 10)
private int id;
@UserFiled(column = "name",type = "varchar",length = 10)
private String name;
@UserFiled(column = "age",type = "int",length = 10)
private int age;
public User() {
}
public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface UserClass{
String db();
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface UserFiled{
String column();
String type();
int length();
AnnocationTest
package annocation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
public class AnnocationTest {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class c1 = Class.forName("annocation.User");
Annotation[] annotations = c1.getAnnotations();
// 获取所有的注解,但是只打印了类的
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
// 通过获取准确字段后获取字段上的注解
Field id = c1.getDeclaredField("id");
Annotation[] annotations1 = id.getAnnotations();
for (Annotation annotation : annotations1) {
System.out.println(annotation);
}
Annotation[] annotations2 = id.getDeclaredAnnotations();
for (Annotation annotation : annotations2) {
System.out.println(annotation);
}
}
}