首页 > 解决方案 > “@Constructor 不适用于构造函数”,同时尝试使用 jdk.nashorn.internal.objects.annotations.Constructor 注释构造函数

问题描述

当我尝试jdk.nashorn.internal.objects.annotations.Constructor在我的类的构造函数上使用注释时,我收到编译错误消息:

@Constructor 不适用于构造函数

IntelliJ 的屏幕截图:

有谁知道它向我显示此错误的原因?

简化代码:

package passengers;

import jdk.nashorn.internal.objects.annotations.Constructor;
import jdk.nashorn.internal.objects.annotations.Getter;

public class Passenger {

    private String name;
    private Stop destination;

    @Constructor //<-- here I see: @Constructor not applicable to constructor
    public Passenger(String name) {
        //..
    }

    @Getter  //<- this works fine
    public String getName() {
        return name;
    }
}

标签: javaintellij-ideaconstructorgetter-setter

解决方案


IDEA 在这一点上是绝对正确的。

当您遇到这种情况时,您应该首先查看@Constructor注解 JavaDoc 或source。你会看到的是

/**
 * Specifies a specific method to be the JavaScript "constructor" function.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Constructor { ... }

这个

@Target(ElementType.METHOD)

表示可以在方法上指定注释。
如果它与构造函数兼容,你会发现

@Target({ElementType.CONSTRUCTOR, ElementType.METHOD})

无论如何,这来自一个internal包,所以你可能不应该使用它。


推荐阅读