如何在 Java 9 中使用新的 BeanInfo Annotations [英] How to use new BeanInfo Annotations in Java 9

查看:18
本文介绍了如何在 Java 9 中使用新的 BeanInfo Annotations的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JEP 256:BeanInfo Annotations 提供了 JavaBeanhref="http://download.java.net/java/jdk9/docs/api/java/beans/BeanProperty.html" rel="nofollow noreferrer">BeanProperty 注释.虽然没有太多文档,但我一直希望这将允许我们使用注释将类上的字段指定为 JavaBean 样式的属性,而无需创建样板 getter/setter 访问器/mutator 方法.

所以:

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 中的@"注释上收到错误消息:

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' 不适用于字段

'@BeanProperty' not applicable to field

编译器报错:

错误:(8, 5) java: 注释类型不适用于这种声明

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?

除了上面链接的 JEP 和 JavaDoc 之外,我没有找到任何文档.

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

我正在试验 Java 9 的最新候选版本,目前是 macOS Sierra 10.12.6 上的 Java 9+181.

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

推荐答案

javadocBeanProperty@Target(METHOD).貌似是自定义PropertyDescriptors 而无需创建 BeanInfo 实现.我不认为它的目的是像 Lombok 那样工作.(谢天谢地——请参阅为什么使用 getter 和 setter? 了解所有显式方法的原因是个好主意.)

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

这篇关于如何在 Java 9 中使用新的 BeanInfo Annotations的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆