如何在带注释的类上生成方法?
我想学习并享受注释的乐趣。这是我的用例:我有一堆基本上具有相同角色的类:根据正则表达式验证视频 URL(第一种方法)并返回相应的嵌入 HTML(另一种方法)。
问题是验证方法总是相同的。我当然可以使用继承,但我希望是否可以创建这样的注释:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.??)
@Inherited
@Documented
public @interface VideoProvider {
String regex();
int group() default 1;
}
像这样处理:
//processor class
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
for (TypeElement annotation : annotations) {
for (Element e : roundEnv.getElementsAnnotatedWith(annotation)) {
if (e.getKind().isClass()) {
//?????
}
}
}
return false;
}
这个想法是动态更改带注释的类以注入执行验证的方法。 这可行吗?
提前致谢!
罗尔夫
I wanna learn and have fun with annotations. Here is my use case: I have got a bunch of classes who basically have the same role: validate a video URL against a regex (1 method) and return the corresponding embedded HTML (another method).
The thing is the validation method is always the same. I could of course use inheritance, but I would like if it is possible to create an annotation like this:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.??)
@Inherited
@Documented
public @interface VideoProvider {
String regex();
int group() default 1;
}
Processed like that:
//processor class
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
for (TypeElement annotation : annotations) {
for (Element e : roundEnv.getElementsAnnotatedWith(annotation)) {
if (e.getKind().isClass()) {
//?????
}
}
}
return false;
}
The idea would be to dynamically change the annotated classes to inject a method that performs the validation.
Is that feasible ?
Thanks in advance!
Rolf
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看看使用java的Proxy类你cglib 增强器 类。这两种解决方案都允许您代理一个类并接管任何方法。
Look at using java's Proxy class you cglib Enhancer class. Both solutions allow you to proxy a class and over take any method.
我认为你做错了---
但是如果你真的想在编译时通过注释处理来实现这一点,你应该看看 可插入注释处理 API
这专门用于向编译过程添加注释驱动的扩展,以执行自动添加方法等操作。
I think you're doing it wrong---
But if you really want to implement this with annotation processing at compile time, you should look at the Pluggable Annotation Processing API
This is specifically for adding annotation-driven extensions to the compilation process, to do things like automatically adding methods.