How to call getClass() from a static method in Java?

刚才在学习Java 使用properties类,遇到这样的错误:

Cannot make a static reference to the non-static method getClass() from the type Object

以前使用过getClass,不晓得怎么用的,后来在stackoverflow看到同样的问题

I have a class that must have some static methods. Inside these static methods I need to call the method getClass() to make the following call:

publicstaticvoid startMusic()
{
  URL songPath=getClass().getClassLoader().getResource("background.midi");
}

 

However Eclipse tells me:

Cannot make a static reference to the non-static method getClass() 
from the type Object

What is the appropriate way to fix this compile time error?

牛人的回答是这样的:

s for the code example in the question, the standard solution is to reference the class explicitly by its name, and it is even possible to do without getClassLoader() call:

classMyClass{
       publicstaticvoid startMusic()
    {
              URL songPath =MyClass.class.getResource("background.midi");
     }
}

  

This approach still has a back side that it is not very safe against copy/paste errors in case you need to replicate this code to a number of similar classes.

And as for the exact question in the headline, there is a trick posted in the adjacent thread:

Class currentClass =newObject(){}.getClass().getEnclosingClass();
 

It uses a nested anonymous Object subclass to get hold of the execution context. This trick has a benefit of being copy/paste safe...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值