Ben Chuanlong Du's Blog

It is never too late to learn.

Example of Using Reflection in Java

In [41]:
import java.lang.reflect.Method; 

class Check { 
    private void privateMethod() { 
        System.out.println("A private method is called from outside");
    } 
    
    private void privateMethodWithParam(String fname, long n) { 
        System.out.println("Hello " + fname + " " + n + ", a private Method is called from outside.");
    }
    
    public void printData() { 
        System.out.println("Public Method"); 
    } 
}
Out[41]:
com.twosigma.beaker.javash.bkr95ac1ac9.Check

Invoke a private method without parameters.

In [42]:
import java.lang.reflect.Method; 

Check check = new Check(); 
// get the private method 
Method method = Check.class.getDeclaredMethod("privateMethod"); 
// make it accessible
method.setAccessible(true); 
// invoke the method
method.invoke(check);
A private method is called from outside
Out[42]:
null

Invoke a private method with parameters.

In [45]:
import java.lang.reflect.Method; 

Check check = new Check(); 
// get the private method 
Method method = Check.class.getDeclaredMethod("privateMethodWithParam", String.class, long.class); 
// make it accessible
method.setAccessible(true); 
// invoke the method
method.invoke(check, "Ben", 2);
Hello Ben 2, a private Method is called from outside.
Out[45]:
null
In [ ]:

Comments