使用默认修饰符(需要Java8+)在一个带注解的接口中会导致错误。

huangapple go评论70阅读模式
英文:

Trying to use default modifier (requires java8+) in an annotated interface yields an error

问题

I am a beginner using spring, I am trying to use default modifier (requires java8+) in an annotated interface. but I am getting an error default modifier is not allowed here does anyone familiar with this issue ? is something to do with spring version or with spring in general ?
I am using springBootVersion=2.1.16.RELEASE

Edit:
I cannot remove the annotation because more annotations involved

@//other annotations
@Documented
public @interface Foo {
    public default String fooName() {
        return this.getClass().getName();
    }
}

java: modifier default not allowed here

英文:

I am a beginner using spring, I am trying to use default modifier (requires java8+) in an annotated interface. but I am getting an error default modifier is not aloud here does anyone familiar with this issue ? is something todo with spring version or with spring in general ?
I am using springBootVersion=2.1.16.RELEASE

Edit:
I cannot remove the annotation because more annotations involved

@//other annotations
@Documented
public @interface Foo {
    public default String fooName() {
        return this.getClass().getName();
    }
}

> java: modifier default not allowed here

答案1

得分: 1

默认方法仅适用于接口。此功能作为Java 8版本的一部分引入。

您在尝试为注解添加默认方法,但是注解不支持默认方法。因此,您会收到错误。

理想情况下,Java中的注解用于为特定类、方法或文件传递元数据。因此,在正常情况下,您的注解不应包含具有方法体的具体方法。

如果您尝试创建一个带有默认方法的接口,请删除@符号。

public interface Foo {
    public default String fooName() {
        return "foo";
    }
}

或者,如果您要创建一个注解,则不应该是默认方法,请删除默认关键字和方法体。

public @interface Foo {
    public String fooName();
}
英文:

The default method is applicable only for the interface. This feature was introduced as part of Java 8 release.

Here you are trying to add default method to annotations, but the default method is not supported for annotation. Due to this, you are getting error.

Ideally, annotations are used in java to pass the meta-data for a particular class, method or files. So in a normal scenario, your annotation should not contain the concrete method with the body.

If you are trying to create an interface with a default method than remove the @.

public interface Foo {
    public default String fooName() {
        return "foo";
    }
}

Or if you are trying to create an annotation then it should not be default method and remove default keyword and the method body.

public @interface Foo {
    public String fooName();
}

huangapple
  • 本文由 发表于 2020年8月13日 13:46:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/63388852.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定