英文:
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的规定:
> 在接口体中的每个成员类型声明都被隐式地声明为public
和static
。
因此,在字段初始化程序中无法访问this
。
绕过此限制的常见方法是提供一个返回所需内容的方法。可能会作为默认方法(需要Java 8+):
public interface Foo {
public default String fooName() {
return this.getClass().getName();
}
}
英文:
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();
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论