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'
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.
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.
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.
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 ...
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.
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 :
In your case, something like this should work :
Method method = clazz.getMethod("foo", null); method.invoke(null, null); // foo returns nothing
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With