Basil Bourque Basil Bourque - 2 months ago 13
Java Question

How to use new BeanInfo Annotations in Java 9

JEP 256: BeanInfo Annotations provides for

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.

VGR VGR
Answer Source

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.)