Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a static method via a class reference

Tags:

class A {     public static void foo() {} }  class B {     public static void foo() {} } 

I have Class clazz = A.class; or B.class;

How do I access this via "clazz" assuming it might be assigned either 'A' or 'B'

like image 858
user339108 Avatar asked Mar 05 '11 09:03

user339108


People also ask

Can we access static method using class?

Static methods have access to class variables (static variables) without using the class's object (instance). Only static data may be accessed by a static method. It is unable to access data that is not static (instance variables). In both static and non-static methods, static methods can be accessed directly.

Can I access static method by using object reference?

Static methods can't access instance methods and instance variables directly. They must use reference to object. And static method can't use this keyword as there is no instance for 'this' to refer to.

How do you access static methods?

A static method can only access static variables; it cannot access instance variables. Since the static method refers to the class, the syntax to call or refer to a static method is: class name. method name. To access a non-static method from a static method, create an instance of the class.

How do you access static methods outside the class?

If we want to access the static numHumans field of the Human class from outside of the Human class this time, we must call the getNumHumans() method because we made the static field private by using the private access modifier, which means the field can only be accessed from within the class its a member of, or belongs ...


2 Answers

It is only possible to access those methods using reflection. You cannot reference a class directly, only an instance of type Class.

To use reflection to invoke methodname(int a, String b):

Method m = clazz.getMethod("methodname", Integer.class, String.class); m.invoke(null, 1, "Hello World!"); 

See Class.getMethod() and Method.invoke()

You may want to think about your design again, to avoid the need to dynamically call static methods.

like image 122
Hendrik Brummermann Avatar answered Sep 22 '22 23:09

Hendrik Brummermann


You can invoke a static method via reflection like this :

Method method = clazz.getMethod("methodname", argstype); Object o = method.invoke(null, args); 

Where argstype is an array of arguments type and args is an array of parameters for the call. More informations on the following links :

  • getMethod()
  • invoke()

In your case, something like this should work :

Method method = clazz.getMethod("foo", null); method.invoke(null, null); // foo returns nothing 
like image 25
krtek Avatar answered Sep 22 '22 23:09

krtek