使方法仅接受特定注释的参数
我有一种方法
public static void injectConfiguration(@Configurable Object bean) {}
,我有一个拥有字段的课程
public class LauncherComponentsHolder {
@Configurable
public RoomDao roomDao;
,我有主要班级,我称这种方法并将他传递给他:
LauncherComponentsHolder root = new LauncherComponentsHolder();
root.roomDao = new RoomDaoImpl();
root.guestDao = new GuestDaoImpl();
root.maintenanceDao = new MaintenanceDaoImpl();
ConfigInjector.injectConfiguration(root.roomDao);
ConfigInjector.injectConfiguration(root.guestDao);
ConfigInjector.injectConfiguration(root.maintenanceDao);
问题是该方法接受了所有3个参数(没有警告,错误,什么都没有),但是只有室多是注释的。注释本身:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER, ElementType.FIELD})
public @interface Configurable {
}
如何做出限制,以便注射configuration(@configurable object bean)
仅接受配置
的注释的字段(或类实例)?
I have a method
public static void injectConfiguration(@Configurable Object bean) {}
And I have a class which holds field
public class LauncherComponentsHolder {
@Configurable
public RoomDao roomDao;
And I have main class, where I call that method and pass him that:
LauncherComponentsHolder root = new LauncherComponentsHolder();
root.roomDao = new RoomDaoImpl();
root.guestDao = new GuestDaoImpl();
root.maintenanceDao = new MaintenanceDaoImpl();
ConfigInjector.injectConfiguration(root.roomDao);
ConfigInjector.injectConfiguration(root.guestDao);
ConfigInjector.injectConfiguration(root.maintenanceDao);
Problem is that the method accepts all the 3 parameters, (no warnings, errors, nothing) however only roomDao is annotated. Annotation itself:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER, ElementType.FIELD})
public @interface Configurable {
}
How to make the restriction, so that injectConfiguration(@Configurable Object bean)
would accept only field (or class instance) annotated with Configurable
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用注释处理器来实现这一目标。
这样的工具的一个示例是 Checker Framework 。
它使您可以在程序中编写类型注释,然后在编译时键入类型注释。如果您程序中的类型注释彼此不一致,则会发出警告。
实现检查的最简单方法是使用 subtyping Checker 。
这是示例来自其手册:
当您调用
Javac
时使用几个额外的命令行参数,javac
在第二次调用sendoverinternet
的第二个调用中,但不是第一个:You can accomplish this by using an annotation processor.
An example of such a tool is the Checker Framework.
It enables you to write type annotations in your program, then it type-checks the type annotations at compile time. It issues a warning if the type annotations in your program are not consistent with one another.
The easiest way for you to implement the checking would be to use the Subtyping Checker.
Here is an example from its manual:
When you invoke
javac
using a couple extra command-line arguments,javac
issues an error for the second invocation ofsendOverInternet
but not the first one: