我有一个类,必须有一些静态方法。在这些静态方法中,我需要调用方法getClass()来进行以下调用:
public static void startMusic() {
URL songPath = getClass().getClassLoader().getResource("background.midi");
}
但是Eclipse告诉我:
Cannot make a static reference to the non-static method getClass()
from the type Object
修复此编译时错误的适当方法是什么?
这个问题的答案
只需使用classname .class而不是getClass()。
宣布伐木工
Since this gets so much attention for a specific usecase--to provide an easy way to insert log declarations--I thought I'd add my thoughts on that. Log frameworks often expect the log to be constrained to a certain context, say a fully-qualified class name. So they are not copy-pastable without modification. Suggestions for paste-safe log declarations are provided in other answers, but they have downsides such as inflating bytecode or adding runtime introspection. I don't recommend these. Copy-paste is an editor concern, so an editor solution is most appropriate.
在IntelliJ中,我建议添加一个Live模板:
使用“log”作为缩写
使用私有静态final org.slf4j。Logger Logger = org.slf4j.LoggerFactory.getLogger($CLASS$.class);作为模板文本。
单击“编辑变量”并使用表达式className()添加CLASS
选中复选框以重新格式化和缩短FQ名称。
将上下文更改为Java: declaration。
现在如果你输入log<tab>它会自动展开到
private static final Logger logger = LoggerFactory.getLogger(ClassName.class);
并自动为您重新格式化和优化导入。