注解
1.注解相关
注解:用于记录一些数据,我们通过反射可以获取到这些属性内容,简化我们配置文件的编写
一、元注解是修饰注解的注解
1.@Target 表示指定注解可以书写的位置
2.@Retention 表示注解的生命周期
a.默认不写为CLASS 表示二进制文件中保留此注解
b.SOURCE 表示在源文件中保留此注解
c.RUNTIME 表示在程序运行过程中保留此注解
3.@Documented 表示在文档注释中保留此注解
4.@Inherited 表示此注解将被子类继承
二、注解属性支持的数据类型 八种基本数据类型 String Class 枚举 和其对应的数组
三、注解的位置,由另外一个元注解@Target来修饰 ,默认不写表示在任何位置 都可以使用
四、注解的属性名,如果注解的属性名为value,那么可以直接写值,否则其他的都要写为 name = value 形式
2.通过反射获取注解的信息
package com.qfedu.test2;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME) // 表示在程序执行过程中通过 反射可以获取到此注解
@Target(ElementType.FIELD) // 表示只能加在字段(属性)上
public @interface Host {
String value();
}
package com.qfedu.test2;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Name {
String value();
}
package com.qfedu.test2;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Password {
String value();
}
package com.qfedu.test2;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Port {
String value();
}
package com.qfedu.test2;
import java.lang.reflect.Field;
/**
* 数据库信息工具类
* 用户名
* 密码
* 连接地址
* 端口号
* @author WHD
*
*/
public class ConnInfo {
@Name("root")
private String name;
@Password("9999")
private String password;
@Host("localhost")
private String host;
@Port("3306")
private String port;
public static void main(String[] args) throws Exception {
Class<?> connClass = Class.forName("com.qfedu.test2.ConnInfo");
// Class<ConnInfo> cla = ConnInfo.class;
Field[] fields = connClass.getDeclaredFields();
System.out.println(fields.length);
for(Field f : fields) {
if(f.isAnnotationPresent(Name.class)) {
Name annotation1 = f.getAnnotation(Name.class);
System.out.println(annotation1.value());
}
if(f.isAnnotationPresent(Password.class)) {
Password annotation2 = f.getAnnotation(Password.class);
System.out.println(annotation2.value());
}
if(f.isAnnotationPresent(Host.class)) {
Host annotation3 = f.getAnnotation(Host.class);
System.out.println(annotation3.value());
}
if(f.isAnnotationPresent(Port.class)) {
Port annotation4 = f.getAnnotation(Port.class);
System.out.println(annotation4.value());
}
}
}
}