Cléssio Mendes
Cléssio Mendes

Reputation: 1016

Calling static methods from a Class type

I'd like to store a class object in a local variable and then call its static methods. Also, the class object should expect descendant types:

class Ancestor {
   static void staticMethod() {
   }
}
class Descendent extends Ancestor {
}

(...)

Class<? extends Ancestor> fool = Descendent.class;
fool.staticMethod() //compilation error 'cannot resolve symbol'

How would you guys solve this?

Upvotes: 0

Views: 2013

Answers (1)

mh-dev
mh-dev

Reputation: 5503

There are multiple errors in you question, but I give you that what comes closest to an answer. First of all be aware that your using default visibility which is package. So the method can only be seen by classes in the same package.

The following snippet from you is not valid:

Class<Ancestor> fool = Descendent.class;

A valid version would be:

 Class<? extends Ancestor> fool = Descendant.class; 

Related to the static method invocation. You cannot invoke static methods of a class with just the class object. It is possible to invoke the method via reflection. This could look like the following:

fool.getDeclaredMethod("staticMethod").invoke(null);

There are two special behaviors in that case.

  1. static methods will be invoked with null as object argument
  2. It does only work on the class object declaring the static method and not for classes extending the class with the static method.

Upvotes: 5

Related Questions