I have a Dummy
class that has a private method called sayHello
. I want to call sayHello
from outside Dummy
. I think it should be possible with reflection but I get an IllegalAccessException
. Any ideas???
Private: The class members declared as private can be accessed only by the functions inside the class. They are not allowed to be accessed directly by any object or function outside the class. Only the member functions or the friend functions are allowed to access the private data members of a class.
Object users can't use private methods directly. The main reason to do this is to have internal methods that make a job easier.
Calling a private method from another Class A private method can be called from another Class by using reflection API. A private method has more accessibility restrictions than other methods. A private method can be accessed from another class using getDeclaredMethod(), setAccessible() and invoke() methods of the java.
To access private variables of parent class in subclass you can use protected or add getters and setters to private variables in parent class.. Show activity on this post. You can't access directly any private variables of a class from outside directly. You can access private member's using getter and setter.
use setAccessible(true)
on your Method object before using its invoke
method.
import java.lang.reflect.*; class Dummy{ private void foo(){ System.out.println("hello foo()"); } } class Test{ public static void main(String[] args) throws Exception { Dummy d = new Dummy(); Method m = Dummy.class.getDeclaredMethod("foo"); //m.invoke(d);// throws java.lang.IllegalAccessException m.setAccessible(true);// Abracadabra m.invoke(d);// now its OK } }
First you gotta get the class, which is pretty straight forward, then get the method by name using getDeclaredMethod
then you need to set the method as accessible by setAccessible
method on the Method
object.
Class<?> clazz = Class.forName("test.Dummy"); Method m = clazz.getDeclaredMethod("sayHello"); m.setAccessible(true); m.invoke(new Dummy());
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