你可以从接口中引用这个吗?

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

How can i reference this from interface

问题

抱歉,我只返回翻译好的部分,不会回答问题。以下是翻译好的内容:

"Hi,我想做类似的事情,但问题是获取并且不能从静态上下文引用这个。例如(简化):

public interface Foo {
     public String fooName = this.getClass().getName();
}

我该如何做?"

英文:

Hi I would like to do something like this but the problem is getting and that this cannot be reference from static context . for example (simplified) :

public interface Foo {
     public String fooName = this.getClass().getName();
}

how can I do it ?

答案1

得分: 3

根据Java 14 JLS,§9.5的规定:
> 在接口体中的每个成员类型声明都被隐式地声明为publicstatic

因此,在字段初始化程序中无法访问this

绕过此限制的常见方法是提供一个返回所需内容的方法。可能会作为默认方法(需要Java 8+):

public interface Foo {
    public default String fooName() {
        return this.getClass().getName();
    }
}

<kbd>Ideone演示</kbd>

英文:

As per Java 14 JLS, §9.5:
> Every member type declaration in the body of an interface is implicitly public and static.

Thus, one cannot access this in a field initializer.

The common way to work around this limitation is to provide a method that returns what is needed. Possibly, as default method (requires Java 8+):

public interface Foo {
    public default String fooName() {
        return this.getClass().getName();
    }
}

<kbd>Ideone demo</kbd>

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

发表评论

匿名网友

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

确定