Java 6-注释处理器和代码添加
我编写了一个自定义注释,其中包含属性和Java 6-注释处理器和代码添加,java,properties,osgi,bytecode,code-injection,Java,Properties,Osgi,Bytecode,Code Injection,我编写了一个自定义注释,其中包含属性和AnnotationProcessor的元数据: @SupportedAnnotationTypes({"<package>.Property"}) public class PropertyProcessor extends AbstractProcessor { @Override public boolean process(Set<? extends TypeElement> annotations,
AnnotationProcessor
的元数据:
@SupportedAnnotationTypes({"<package>.Property"})
public class PropertyProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
// Get messager object
Messager messager = processingEnv.getMessager();
// Iterate through the annotations
for(TypeElement typeElement : annotations) {
// Iterate through the annotated elements
for(Element element : roundEnv.getElementsAnnotatedWith(typeElement)) {
// Get Property annotation
Property property = element.getAnnotation(Property.class);
}
}
return false;
}
}
@SupportedAnnotationTypes({.Property})
公共类PropertyProcessor扩展了AbstractProcessor{
@凌驾
publicbooleanprocess(Set简而言之,在注释处理过程中不应该更改源代码
我最近遇到过这样一种情况,答案并不令人满意(请参阅)。我的解决方案是使用内部javac api以编程方式添加所需的代码。有关详细信息,请参阅
我从他们的源代码开始,扔掉所有我不需要的东西,我认为你不会找到更好的起点
顺便说一句,Javassist可能不会有帮助,因为您处理的是源代码树,而不是字节码。如果您想使用字节码操纵库,您可以在编译后静态执行,也可以在加载类时动态执行,但不能在注释处理期间执行,因为这是预编译步骤。您尝试过吗
Google Guice可以让你通过拦截方法进行一些面向方面的编程。如果你只需要这么做,你可以实现一个MethodInterceptor,它可以让你在运行时覆盖方法。它非常适合隔离交叉关注点
例如,假设您想阻止某个方法在周末执行,您可以将其注释为:
@Property
public class SomeClass {
public Receipt doSometing() {
// Do something
}
}
定义MethodInterceptor:
public class PropertyInterceptor implements MethodInterceptor {
public Object invoke(MethodInvocation invocation) throws Throwable {
// For example prevent the classes annotated with @Property
// from being called on weekends
Calendar today = new GregorianCalendar();
if (today.getDisplayName(DAY_OF_WEEK, LONG, ENGLISH).startsWith("S")) {
throw new IllegalStateException(
invocation.getMethod().getName() + " not allowed on weekends!");
}
return invocation.proceed();
}
}
然后将拦截器绑定到注释:
public class PropertyModule extends AbstractModule {
protected void configure() {
PropertyInterceptor propertyInterceptor = new PropertyInterceptor();
bindInterceptor(Matchers.annotatedWith(Property.class),
Matchers.any(), propertyInterceptor);
}
}
注释处理并不是为了改变现有的类——它只是为了生成额外的代码/资源(以类为基础,否则在只重新编译修改过的源代码时会遇到麻烦)
不久前,我试图解决一个类似的问题:我非常喜欢程序处理器的想法(甚至更喜欢IDE集成),但当时它并不稳定
根据您的用例,AOP工具(例如:)可以比Spoon更适合您,当然,您也可以始终使用源代码生成器或实现全面的DSL(看看奇妙之处)
取决于规模、周转率和“智力惯性”对于您的团队伙伴-您最好能忍受普通java带来的痛苦,而不是引入新工具/技术、组建同事并将新工具集成到CI系统中。仔细权衡成本/收益。一个问题-为什么需要这样做?不能用另一种方式实现吗?如果不使用APT或此API,我需要为每个属性同时注释setter和getter方法,但如果这样做有效,我将完全控制代码的生成方式。这不是一个纯粹的业务问题,我想知道这是否可行