注解
分类:
-
JDK内置注解有:@Override、@SuppressWarning等
-
元注解:解释注解的注解。元注解有:@Target 表明注解作用与类的什么位置(类、属性、方法)
@Retention 表明注解的运行实际(运行时、编译时,默认编译期,比如@Oveerride)
注解的作用
编译检查、生成文档、运行时动态处理、编译时动态处理
反射
在程序运行期间动态创建对象,动态获取类的信息
反射应用场景
反射和自定义注解结合使用
各种框架大量使用了反射机制,比如Spring的@Component、@Value
注解相当于一个标识,注解的实现基于反射
public class Generic {
public static void main(String[] args) throws Exception {
// 利用反射获取对象
Class<A> aClass = A.class;
MyComponent myComponent = aClass.getDeclaredAnnotation(MyComponent.class);
System.out.println(myComponent);
if(myComponent != null){
// 创建对象
Constructor<A> constructor = aClass.getConstructor(null);
A a = constructor.newInstance(null);
Field[] fields = aClass.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
MyValue annotation = field.getAnnotation(MyValue.class);
if(annotation != null){
if(field.getType().getName().equals("java.lang.Integer")){
field.set(a, Integer.parseInt(annotation.value()));
}else if(field.getType().getName().equals("java.lang.String")){
field.set(a, annotation.value());
}
}
}
System.out.println(a);
}
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface MyValue{
String value();
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface MyComponent{
}
@Data
@MyComponent
class A{
@MyValue("1")
private Integer id;
@MyValue("zs")
private String name;
}
反射机制的优缺点
让代码更灵活,为各种框架提供了开箱即用的功能
缺点是:在运行时有了获取类信息的能力,但是增加了安全问题。反射的性能稍微差点。