简体   繁体   中英

How to use new BeanInfo Annotations in Java 9

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.

The javadoc says BeanProperty is @Target(METHOD) . Looks like it's a way to customize PropertyDescriptor s 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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM