注解
什么是注解
一种特殊的注释
注解的作用
- 编译器可以使用注解来检测错误或抑制警告。
- 处理注解信息以生成代码或配置文件等。
- 可以在运行时检查某些注解并处理。
注解的缺点
- 侵入式编程,增加耦合度
- 产生问题定位困难
- 需要利用反射来获取属性,破坏代码封装性
注解的解析方式
- 编译期直接的扫描:JDK内置注解类(
@Override
) - 运行期的反射:自定义注解类(
@Component
)
怎么自定义注解
- 创建注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface NotNull {
}
- 创建注解处理器
public class NotNullChecker {
public static void check(Object obj) throws IllegalAccessException {
Class<?> clazz = obj.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(NotNull.class)) {
// 确保可以访问私有字段
field.setAccessible(true);
if (field.get(obj) == null) {
throw new NullPointerException();
}
}
}
}
- 测试并使用
public class User {
@NotNull
private String name;
}
public class Main {
public static void main(String[] args) {
User user1 = new User("John");
User user2 = new User(null);
try {
NotNullChecker.check(user1);
System.out.println("user1 passed the null check.");
} catch (Exception e) {
System.out.println(e.getMessage());
}
try {
NotNullChecker.check(user2);
System.out.println("user2 passed the null check.");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}