Calling private method of other class which is not accessible.

Hey Guys,

Here you will get to know you can access private method using invoke method.

Generally Private methods can usually only be accessed from within the same class. We can’t access those private methods from outside class. However, It’s possible to access the private methods from outside class using Java's Reflection API.

I have written this code in Android. Here is the code:

public class MainActivity extends AppCompatActivity {

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        Fruit d = new Fruit();
        Method m = null;
        try {
            m = Fruit.class.getDeclaredMethod("fruitname");
            m.setAccessible(true);
            m.invoke(d);
       } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

class Fruit{
    private void fruitname(){
        System.out.println("grapes");
    }
}
 
 
Hope this will helps you.
Thanks,


Comments

Popular posts from this blog

How to Use Co-routine For Taking Touch Event in Unity(Mouse Event And Keyboard KeyEvent), Also Explained How to call coroutine from other script

post1