像`this.class`而不是`ClassName.class`的东西?

时间:2015-04-07 13:38:58

标签: java android

当我定义Android服务类时,我经常定义(实际上是复制和粘贴)使用给定数据启动服务的静态方法:

public class MyShinyBackgroundService extends Service 
{
    ...
    // start this service if it's not running; pass data
    public static void startServiceWithData(String data, Context context) {
        Intent intent = new Intent(context, MyBackgroundService.class);
        intent.setAction(MY_ACTION);
        intent.putExtra(DATA_KEY, data);
        context.startService(intent);
    }
}

可能你已经看到了这个bug:这个方法调用了错误的服务。 (一个愚蠢的副本和粘贴错误。如果我能编写类似this.class的内容,就不会发生这种情况,但遗憾的是它在语法上并不合适。)

Java中是否有一种方法可以从除类名之外的静态方法引用"此类" .class

修改

我不同意@CommonsWare关于这个问题是重复的,因为我需要.class而不是类名;尽管如此,this answer确实提出了一个足够好的黑客攻击,使代码可以复制/粘贴安全:

Intent intent = new Intent(context, new Object(){}.getClass().getEnclosingClass());

new Object(){}中的大括号很重要!!!)

我绝对不喜欢一种不太讨厌的解决方案,所以我要求读者投票重新开启这个问题。

编辑2

现在,我倾向于将thisClass定义为私有静态类成员(私有,因为将此类成员从其他地方继承或引用是错误的{ {1}}与MyShinyBackgroundService.thisClass相同。非常愚蠢的是,MyShinyBackgroundService.class是Java中的保留字,因此必须通过别名引用字段class

class

0 个答案:

没有答案
相关问题