Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a private method from outside a java class

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???

like image 293
Hamed Rajabi Avatar asked Jul 01 '12 13:07

Hamed Rajabi


People also ask

Can private methods be accessed outside of the class?

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.

Can we call private method using object?

Object users can't use private methods directly. The main reason to do this is to have internal methods that make a job easier.

Can you call a method from another class in java?

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.

How do you access private instance outside the class or subclass?

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.


2 Answers

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     } } 
like image 74
Pshemo Avatar answered Sep 28 '22 18:09

Pshemo


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()); 
like image 36
Mostafa Zeinali Avatar answered Sep 28 '22 17:09

Mostafa Zeinali