Jan 23, 2014

How to call private function of another class

In this tutorial we will see how we can call a private function of another class. So lets take an example (not so serious example this time). Say we have a class called SpiderMan that has private variable name and one private method called getMyName that will accept one String variable (this is basically to show how to pass arguments while calling such function) and it will return value of private variable name. So following is our class.

package com.techcielo.corejava.reflection;

public class SpiderMan {
       private String name="Peter Parker";
       private String getMyName(String visitorName){
              System.out.println("Who's knocking?...Its.."+visitorName);
              return name;

Now lets have another class called GreenGoblic that wants to identify what to find who is SpiderMan so it will use reflection API. It will first get Class object for SpiderMan class and then get instance of Method class by using getDeclaredMethod function on this Class object. Second argument of this function will be argument that we will pass to the function. This will take care of function over loading. Once we have access to this Method class we will invoke function invoke on this instance. We can pass list of objects that we want to pass to function that we want to execute. So following will be our class.

package com.techcielo.corejava.reflection;

import java.lang.reflect.Method;

public class GreenGoblin {
       public static void main(String[] args) {
                     Object obj = Class.forName("com.techcielo.corejava.reflection.SpiderMan").newInstance();
                     Method meth = obj.getClass().getDeclaredMethod("getMyName", String.class);
                     String name = (String) meth.invoke(obj, "Green Goblin");
                     System.out.println("Got you Spidy...you are..."+name);
              catch (Exception e) {

When we execute this class following is what we will get…
Who's knocking?...Its..Green Goblin
Got you Spidy...you are...Peter Parker