面试题答案
一键面试处理思路
- 捕获异常:在通过反射获取注解以及访问注解属性时,使用
try-catch
块捕获可能出现的异常,如NoSuchAnnotationException
(未找到注解)、IllegalArgumentException
(属性值格式不正确等)。 - 记录日志:在
catch
块中记录详细的错误信息,方便排查问题。可以使用日志框架,如log4j
、slf4j
等,这里以System.out.println
简单代替日志记录。 - 返回默认值或进行适当处理:对于属性值格式不正确的情况,可以返回默认值,或者根据业务需求进行其他处理。
代码示例
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
// 定义自定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface MyAnnotation {
String value() default "";
}
class MyClass {
@MyAnnotation("abc123")
private String myField;
}
public class AnnotationErrorHandling {
public static void main(String[] args) {
MyClass myClass = new MyClass();
Class<?> clazz = myClass.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
try {
MyAnnotation annotation = field.getAnnotation(MyAnnotation.class);
if (annotation != null) {
String value = annotation.value();
// 这里假设需要将value解析为整数,可能会出现格式不正确的情况
try {
int num = Integer.parseInt(value);
System.out.println("解析成功: " + num);
} catch (NumberFormatException e) {
System.out.println("属性值格式不正确,使用默认值: 0");
}
}
} catch (Exception e) {
System.out.println("获取或使用注解时出错: " + e.getMessage());
}
}
}
}
在上述代码中,定义了一个自定义注解@MyAnnotation
,并在MyClass
类的myField
字段上使用该注解。在main
方法中,通过反射获取字段上的注解,并尝试将注解的value
属性解析为整数。如果解析失败(即属性值格式不正确),捕获NumberFormatException
异常并给出提示使用默认值。如果在获取注解过程中出现其他异常,也会捕获并打印错误信息。