注解
-
Annotation从JDK5.0开始引入的新技术
-
Annotation的作用:
- 不是程序本身,可以对程序做出解释。
- 可以被其他程序读取
-
Annotation的格式:
- 注解是以“@注释名”在代码中存在的,还可以添加一些参数值,
-
Annotation在哪里使用?
- 可以附加在package,class,method,field上面,详单与给他们添加了额外的辅助信息,我们可以通过反射机制对这些数据进行访问。
内置注解
- @Override:定义在java.lang.Override中,此注解只适用于修饰方法,表示一个方法声明打算重写父类中另一个方法声明
- @Deprecated:定义在java.lang.Deprecated中,此只是可以用于修饰方法,属性,类。表示不鼓励程序员使用这样的元素,通常因为存在更好的选择。
- @SuppressWarnings:定义在java.lang.SuppressWarnings中,用来抑制编译时的警告信息,需要添加一个参数才能正确使用,这些参数都是已经定义好了的。
元注解
元注解的作用就是负责注解其他注解,Java定义了4个标准的meta-annotation类型,他们被用来提供对其他annotation类型作说明。
这些类型和他们所支持的类在java.lang.annotation包中可以找到
- @Target:用于描述注解的使用范围(即:被描述的注解可以用在什么地方)
- @Retention:表示需要在什么级别保存该注解,用于表述注解的声明周期
- (SOURCE<CLASS<RUNTIME)
- @Document:说明该注解被包含在javadoc中
- @Inherited:说明子类可以继承父类中的该注解
public class Test02{
@MyAnnotation
public void test(){
}
//Target表示我们的注解可以用在哪些地方。
@Target(value={ElementType.METHOD,ElementType.TYPE})
//表示我们的注解在什么地方还有效
//RUNTIME > CLASS > SOURCE
@Retention(value = RetentionPolicy.RUNTIME)
//表示是否将我们的注解生成在Javadoc文档中
@Documented
//表示子类乐意继承父类的注解
@Inherited
@interface MyAnnotation{
}
}
自定义注解
使用@interface
自定义注解时,自动继承了java.lang.annotation.Annotation接口
- 分析:
@interface
用来声明一个注解,格式:public @interface
注解名{定义内容}- 其中的每一个方法实际上时声明了一个配置参数。
- 方法的名称就是参数的名称
- 返回值类型就是参数的类型
- 可以通过default来声明参数的默认值
- 如果只有一个参数成员,一般参数名为value,当只有一个参数名为value时,使用注解时可以省略value
- 注解元素要有值,我们定义注解元素,经常使用空字符串0作为默认值。
public class Test{
@MyAnnotation2(name="123",schools = {"ewq","ewq"})
public void test(){}
}
@Target({ElemenType.TYPE,ElementTYPE.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2{
String name() default "";
int age() default 0;
int id() default -1;//如果默认值为-1,代表不存在。
String[] schools() default {"321","123"};
}
通过注解和反射完成对象映射关系
public class Test12{
public static void main(String[] args){
Class c1 = Class.forname("com.kuang.reflections.Student2");
Annotation[] annotations = c1.getAnnotations();
for(Annotation annotation : annotations){
System.out.println(annotation);
}
Tableeee table = (Tableeee) c1.getAnnotation(Tableeee.class);
String value = tableeee.value();
Field f = c1.getDeclaredField("name");
Fieldddd annotation = f.getAnnotation(Fieldddd.class);
annotation.culumnName;
annotation.type;
annotation.length;
}
}
@Tableeee("student")
class Student2{
@Fieldddd(columnName = "db_id",type = "int", length = 10)
int id;
@Fieldddd(columnName = "db_name",type = "int", length = 10)
String name;
}
//类名的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Tableeee{
String value();
}
//属性的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Fieldddd{
String columnName();
String type();
int length();
}