如何在 Java 9 中使用新的 BeanInfo 注释
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.
所以这个:
public class Person {
private String name ;
public String getName( ) {
return this.name ;
}
public void setName( String nameArg ) {
this.name = nameArg ;
}
}
……会变成这样:
import java.beans.BeanProperty;
public class Person {
@BeanProperty
public String name ;
}
然而,当我在 IntelliJ 2017.2.2 的 Java 9 项目中尝试此操作时,我在“@”注释的 IDE 中收到错误消息:
'@BeanProperty' not applicable to field
编译器报告错误:
Error:(8, 5) java: annotation type not applicable to this kind of declaration
➠ 我是否误解了这些新注释的用途?还是我有语法问题?
除了上面链接的 JEP 和 JavaDoc,我没有找到任何文档。
我正在试验 Java 9 的最新候选版本,目前在 macOS Sierra 10.12.6 上是 Java 9+181。
出于所有原因,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? 显式方法是一个好主意。)
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.
所以这个:
public class Person {
private String name ;
public String getName( ) {
return this.name ;
}
public void setName( String nameArg ) {
this.name = nameArg ;
}
}
……会变成这样:
import java.beans.BeanProperty;
public class Person {
@BeanProperty
public String name ;
}
然而,当我在 IntelliJ 2017.2.2 的 Java 9 项目中尝试此操作时,我在“@”注释的 IDE 中收到错误消息:
'@BeanProperty' not applicable to field
编译器报告错误:
Error:(8, 5) java: annotation type not applicable to this kind of declaration
➠ 我是否误解了这些新注释的用途?还是我有语法问题?
除了上面链接的 JEP 和 JavaDoc,我没有找到任何文档。
我正在试验 Java 9 的最新候选版本,目前在 macOS Sierra 10.12.6 上是 Java 9+181。
出于所有原因,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? 显式方法是一个好主意。)