1

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);
}
Community
  • 1
  • 1
18446744073709551615
  • 16,368
  • 4
  • 94
  • 127
  • Why wouldn't you want to use this.class? – holtc Apr 07 '15 at 13:40
  • 1
    @holtc Because the method is `static`? – thefourtheye Apr 07 '15 at 13:41
  • 7
    Moral of the story: don't recklessly copy&paste code around – Tim Apr 07 '15 at 13:41
  • You could try and pass in the class when executing the static service public static void startServiceWithData(String data, Context context, Class> cls) { Intent intent = new Intent(context, cls); intent.setAction(MY_ACTION); intent.putExtra(DATA_KEY, data); context.startService(intent); } – Proxy32 Apr 07 '15 at 13:47
  • 1
    I am not sure if I agree with the dupe @CommonsWare. – thefourtheye Apr 07 '15 at 13:54
  • Probably abusing the stacktrace or with the creation of an anonymous class one might receive the class name as String, and then do a `Class.forName`. And being called pervert. – Joop Eggen Apr 07 '15 at 14:05

0 Answers0