Can annotations be used for code injection?

前端 未结 4 1624
南方客
南方客 2021-02-08 18:24

I realise that this might be a question that has been asked and answered, but please bear with me.

I want to know if it is possible to use annotations to inject code int

4条回答
  •  攒了一身酷
    2021-02-08 18:39

    You can do this, but you're not supposed to modify the class containing the annotations. (The trick you link to uses the compile tree api to modify the bytecode being generated...) This is not supported and will probably be guarded against in later Java SDKs.

    The proper way to do it is to generate a superclass, subclass or wrapper class.

    I've written a set of annotations that generate getters/setters and other fun stuff. I generate a superclass.

    See http://code.google.com/p/javadude/wiki/Annotations

    You can do things like

    package sample;
    
    import com.javadude.annotation.Bean;
    import com.javadude.annotation.Property;
    import com.javadude.annotation.PropertyKind;
    
    @Bean(properties={
        @Property(name="name"),
        @Property(name="phone", bound=true),
        @Property(name="friend", type=Person.class, kind=PropertyKind.LIST)
    }) 
    public class Person extends PersonGen {
    }
    

    and it'll generate PersonGen for you with the fields/getters/setters and bound property support.

提交回复
热议问题