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

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


当前回答

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

其他回答

试试这样的方法。这对我很管用。Logg(班级名称)

    String level= "";

    Properties prop = new Properties();

    InputStream in =
            Logg.class.getResourceAsStream("resources\\config");

    if (in != null) {
        prop.load(in);
    } else {
        throw new FileNotFoundException("property file '" + in + "' not found in the classpath");
    }

    level = prop.getProperty("Level");

这个问题的答案

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

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

假设有一个Utility类,那么示例代码将是-

    URL url = Utility.class.getClassLoader().getResource("customLocation/".concat("abc.txt"));

CustomLocation -如果资源中有任何文件夹结构,则删除此字符串文字。

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

试一试

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

Or

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