我有一个类,必须有一些静态方法。在这些静态方法中,我需要调用方法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

修复此编译时错误的适当方法是什么?


当前回答

我自己也在努力解决这个问题。一个很好的技巧是在静态上下文中使用当前线程来获取ClassLoader。这也可以在Hadoop MapReduce中工作。其他方法在本地运行时有效,但在MapReduce中使用时返回空InputStream。

public static InputStream getResource(String resource) throws Exception {
   ClassLoader cl = Thread.currentThread().getContextClassLoader();
   InputStream is = cl.getResourceAsStream(resource);
   return is;
}

其他回答

在Java7+中,你可以在静态方法/字段中做到这一点:

MethodHandles.lookup().lookupClass()

这个问题的答案

只需使用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);

并自动为您重新格式化和优化导入。

我也有同样的问题! 但要解决它,只需修改您的代码如下。

public static void startMusic() {
URL songPath = YouClassName.class.getClassLoader().getResource("background.midi");
}

这对我来说很好,希望它也会对你很好。

简单地使用类文字,即NameOfClass.class

试一试

Thread.currentThread().getStackTrace()[1].getClassName()

Or

Thread.currentThread().getStackTrace()[2].getClassName()