java - 仅限公共访问约束的注释
问题描述
我想强制这个注释只能放在公共成员上,无论是字段还是方法。这可能吗?我对这个主题的简短研究说不。
@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 "";
}
}
解决方案
无法在注释本身中配置它,但如果你有一个,你可以在编译时注释处理器中进行配置。如果带注释的元素无效,只需抛出异常即可。
如果您只在运行时处理注释,那将无济于事。您可以触发运行时异常,但不会出现编译错误。
推荐阅读
- reactjs - 重新渲染时不会触发 useEffect
- javascript - `Cannot GET /apiv1/accounts` - 嵌套路由在 Express.js 中不起作用
- android - 如何在 Android 中创建新的硬件设备传感器?
- excel - 用零将数字格式化为千、百万、十亿
- r - 如果另一列中的值对于特定字符串是不变的,则通过分组拆分数据框并删除该组
- javascript - 从 Create React App 扩展 TypeScript ESLint 配置
- python - 如何删除数据框中包含 Nan 值的列?
- node.js - 在 ElectronJS (asar) 中编写 JSON 文件
- c++ - Makefile - 链接器输入文件未使用,因为链接未完成
- html - 用户使用邮政编码数据库输入邮政编码时自动填充状态|Django|JQuery|UI