How to use new BeanInfo Annotations in Java 9

喜夏-厌秋 提交于 2019-12-12 04:32:56

问题


JEP 256: BeanInfo Annotations provides for JavaBean and BeanProperty annotations. While there is not much documentation, I have been hoping this would allow us to use annotations to designate fields on a class as being JavaBean-style properties without having to create boilerplate getter/setter accessor/mutator methods.

So this:

public class Person {

    private String name ;

    public String getName( ) {
        return this.name ;
    }

    public void setName( String nameArg ) {
        this.name = nameArg ;
    }

}

…would become this:

import java.beans.BeanProperty;

public class Person {

    @BeanProperty
    public String name ;

}

Yet when I try this in a Java 9 project in IntelliJ 2017.2.2, I get error in the IDE on the "@" annotation saying:

'@BeanProperty' not applicable to field

Compiler reports error:

Error:(8, 5) java: annotation type not applicable to this kind of declaration

➠ Have I misunderstood the purpose of these new annotations? Or do I have some syntax problem?

I have not found any documentation other than the JEP and JavaDoc linked above.

I am experimenting with the recent release candidates for Java 9, currently Java 9+181 on macOS Sierra 10.12.6.


回答1:


The javadoc says BeanProperty is @Target(METHOD). Looks like it’s a way to customize PropertyDescriptors without having to create a BeanInfo implementation. I don’t think it was intended to work like Lombok. (And thank goodness—see Why use getters and setters? for all the reasons explicit methods are a good idea.)



来源:https://stackoverflow.com/questions/45776211/how-to-use-new-beaninfo-annotations-in-java-9

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!