Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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,





This post first appeared on Unity Coroutine, please read the originial post: here

Share the post

Calling private method of other class which is not accessible.

×

Subscribe to Unity Coroutine

Get updates delivered right to your inbox!

Thank you for your subscription

×