/**
* this is my class, yadayada. Needs to be subclassed to be useful.
*/
public abstract class MyClass {
...
public static void myMethod() {
// What is the name of the subclass that's using this?
System.out.println("Called from class " + this.getClass().class.getName());
// Doesn't work because there's no "this" in a static method.
}
}
Edit: this is what I want to happen:
public class FooClass extends MyClass {
...
}
FooClass.myMethod(); // I would like this to print "Called from class FooClass"
I’m all out of ideas.
Edit: And for those who wonder why I’m doing it this way, it’s actually an Android question of sorts.
Android defines a class called BroadcastReceiver. You subclass this and register your subclass with the system. When an appropriate broadcast is sent, the system creates an instance of your subclass and calls one of its methods.
I want to create my own BroadcastReceiver subclass that contains a static method for registering itself. But I also want it to be subclassable. It sort of looks like this:
/**
* My special-purpose BroadcastReceiver. Subclass this to use it.
*/
public class MyClass extends BroadcastReceiver {
public static scheduleAnAlarm(long when) {
// do some class-specific stuff
AlarmManager.scheduleBroadcast(MyClass.class, when);
}
public void onBroadcast() {
System.out.println("You should subclass MyClass for it to be useful");
}
}
My problem is that I want to register the subclass to be instantiated, not MyClass.
You can’t. That is you cannot get the
classof a subclass from astaticmethod.When Java invokes a
staticmethod on a class (even one that isabstract) no subclass is required therefore none is loaded by the class loader. Therefore there is not necessarily any subclass to get. Even if there was, there could be multiple subclasses so how could Java decide which one you want?Edit, even with your edit you can’t get the subclass. There is a trick you can use with exceptions to get the calling class. You can throw / catch an exception and then walk down the stack trace one level to get the calling method / class. Not recommended!