Using Java Annotations - Generating Code

前端 未结 2 989
闹比i
闹比i 2021-01-06 08:27

I\'m using java 6 annotation processing api. I have followed the following excellent tutorial for creating an annotation processor that displays a message at build-time:

2条回答
  •  时光取名叫无心
    2021-01-06 08:37

    I don't believe Java supports runtime type mutation, meaning to modify the members on a given class you'd have to drop back to a compile time preprocessor or to a bytecode modification scheme.

    I'd be able to point you in a better direction if I understood the "why" behind this question, but in the mean time, dynamic proxy classes might get you to where you want to be (JavaWorld article).

    From the documentation:

    A dynamic proxy class is a class that implements a list of interfaces specified at runtime such that a method invocation through one of the interfaces on an instance of the class will be encoded and dispatched to another object through a uniform interface. Thus, a dynamic proxy class can be used to create a type-safe proxy object for a list of interfaces without requiring pre-generation of the proxy class, such as with compile-time tools. Method invocations on an instance of a dynamic proxy class are dispatched to a single method in the instance's invocation handler, and they are encoded with a java.lang.reflect.Method object identifying the method that was invoked and an array of type Object containing the arguments.

    Here's a decent tutorial on using Spring to inject dynamic proxies based on custom annotations. I think this is probably closest to the behavior you're after.

提交回复
热议问题