Sometimes it is useful to get the type name from static invoke, see this example:
class Base {
private static void funImpl(Class<? extends Base> type) {
...
}
public static void fun() {
fun(Base.class);
}
}
class User extends Base {
public static void fun() {
fun(User.class);
}
}
Here fun() is declared for each subclass. So, can I write something like this?
class Base {
private static void funImpl(Class<? extends Base> type) {
...
}
public static void fun() {
Class<?> leftHandClass = System.getLeftHandClass(); // Error: d'oh...
funImpl(leftHandClass);
}
}
class User extends Base {
}
Agreed. Rather than the superclass having to be “told” what subclass is using it, you do it the other way around and declare abstract methods in the superclass for the subclasses to implement. That way, instead of having one big class that has a bunch of case statements to handle each of its subclasses, the code specific to each subclass goes in the subclass.
If your problem is that you want your subclass instances to be singletons (i.e. so as to use a static method), consider using an enumeration. So rather than calling a static method on a class, you call an instance method on the enumeration constant: SQUARE.fun() etc.