When I define Android service classes, I often define (in fact, copy&paste) static methods that start the service with given data:
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);
}
}
Probably you already see the bug: this method invokes a wrong service. (A stupid copy&paste bug. It would not happen if I could write something like this.class
, but unfortunately it is not syntactically valid.)
Is there a way in Java to reference the .class
of "this class" from a static method other than by class name?
EDIT
I disagree with @CommonsWare about this question being duplicate because I need the .class
rather than class name; nevertheless, this answer indeed suggested a good enough hack that makes the code copy/paste-safe:
Intent intent = new Intent(context, new Object(){}.getClass().getEnclosingClass());
(the braces in new Object(){}
are important!!!)
I definitely would prefer a less hackish solution, so I ask the readers to vote for reopening this question.
EDIT 2
Now I'm inclined to define thisClass
as a private static class member (private because it would be wrong to let this class member be inherited or referenced from elsewhere since MyShinyBackgroundService.thisClass
is the same as MyShinyBackgroundService.class
). It is really stupid that class
is a reserved word in Java so that the field class
must be referenced via an alias.
private static Class thisClass = MyShinyBackgroundService.class;
...
public static void startServiceFrom(Context someContext) {
Intent intent = new Intent(someContext, thisClass);
someContext.startService(intent);
}