Invoking Private methods in Java

Sunday, December 02, 2007

A private method, in Java OOP implementation, is a method which can be invoked *only* by code in the same, instances of other classes cannot have access to that method. Right.
For example, given the following class:

package it.px.intro;

public class MyClass {

private void getMessage() {
System.out.println("This method is it is not visible...");

Trying to invoke the getMessage() method, the compiler complains with:

it\px\intro\ getMessage() has private access
in it.px.intro.MyClass

1 error

So, it is not possible to invoke a private method.
Well...there is another chance...Java Reflection.

Compile and run the following code, for example:

package it.px.intro;

import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;

public class CuriousClass {

public void hack() {
try {

Class c = MyClass.class;
MyClass myObj = new MyClass();

Method[] methods = c.getDeclaredMethods();
for (Method m : methods) {
m.invoke(myObj, new Object[]{});
} catch (Exception ex) {
Logger.getLogger(CuriousClass.class.getName()).log(Level.SEVERE, null, ex);


public static void main(String[] args) {
CuriousClass i = new CuriousClass();

Anything strange?

You Might Also Like

0 commenti