首页 > 解决方案 > 仅限公共访问约束的注释

问题描述

我想强制这个注释只能放在公共成员上,无论是字段还是方法。这可能吗?我对这个主题的简短研究说不。

@Target({ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface CsvAttribute {
     String columnName();
     int position();
}

我的目标是在没有 try-catch 块的情况下实现这一目标。既然我可以访问该对象,我可以在没有反射的情况下做到这一点吗?

public abstract class CsvExportable {

protected final Map<Integer, String> convertFieldsToMap(){
    final Method[] m = this.getClass().getDeclaredMethods();
    return new ArrayList<>(Arrays.asList(m)).stream()
            .filter(p -> p.isAnnotationPresent(CsvAttribute.class))
            .collect(Collectors.toMap(
                    p -> p.getAnnotation(CsvAttribute.class).position(),
                    p -> this.invokeGetter(p)));
}

private String invokeGetter(Method m){
    try {
        return Objects.toString(m.invoke(this), "");
    } catch (IllegalAccessException | InvocationTargetException e) {
        LOG.error("@CsvAttribute annotation must be placed on public getters!");
        e.printStackTrace();
    }
    return "";
}

}

标签: javareflectionannotations

解决方案


无法在注释本身中配置它,但如果你有一个,你可以在编译时注释处理器中进行配置。如果带注释的元素无效,只需抛出异常即可。

如果您只在运行时处理注释,那将无济于事。您可以触发运行时异常,但不会出现编译错误。


推荐阅读