2

I have a singleton class which receives callbacks and handles them, but the class is never called from within the source code. The problem is that Java does not initialize this class because it is not used in the source code, so I will never receive the callbacks. I already thought about calling it manually but I'd prefer it if the class would initialize automatically.

I already tried to use the static initializer, but this is not called either.

Question: what would be the best way to initialize this static class?

private static PushNotificationReceiver receiver = new PushNotificationReceiver();

private PushNotificationReceiver() { }

public static PushNotificationReceiver getInstance() { return receiver; }

private static final String TAG = "MsgService";

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    //Message is received, do something.
}

Edit 1: I found a solution, but this is just by calling the class manually. Is there really no other better alternative which will do this automatically? https://stackoverflow.com/a/9130560/4653908

Community
  • 1
  • 1
Guido
  • 1,161
  • 3
  • 12
  • 33
  • Basically you want your application to start and load your class automatically, without you calling it directly? If that's the case, you may want to take a look at Classloaders (https://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html) and build your own implementation that loads your class on startup. Then the static initializer would be called. – Aurasphere Apr 24 '17 at 10:53
  • 2
    Sorry, but the best practice *would be* to call the class manually. In fact, it would be better to get rid of global state completely and just pass an instance of `PushNotificationReceiver` to the classes that need it. Think about how much easier to debug your code would be this way. That being said, if you *really want* a singleton pattern, you should just have `getInstance` create a new receiver if none exists. After all, your class is still useless until another class starts trying to send events to it. – ostrichofevil Apr 24 '17 at 10:54
  • @ostrichofevil The problem is that no other class is using this. I'm extending another class which receives callbacks, and the `PushNotificationReceiver` is handling those callbacks. – Guido Apr 24 '17 at 10:56
  • If no other class is using it, who is sending it callbacks? Are other classes using the super-class only? – ostrichofevil Apr 24 '17 at 10:59
  • Your question lacks context. If the class is not used, you do not need it. If the class is an extension of a FirebaseMessageService, you should clearly say so (the onMessageReceived(RemoteMessage) looks like that). If that is true, your service should be registered somewhere in the app manifest, but there's others who know that android-stuff better than me. But to reach these people, add more context to your question and add some helpful tags please. – mtj Apr 24 '17 at 13:56

0 Answers0