Monday, April 12, 2010

Executing private methods of an object

For a long time I thought Private methods of a class cannot be called outside of the class. That was till I read Effective Java. I gave this a try and voila. I could.

Here is a simple class and corresponding main code to execute private method. pretty cool. So the next time you do not want your private method to be called at all consider throwing an Exception from within the method.

MainWrapper.java
=============
package com.rixon.scjp.samples;

import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Method;

public class MainWrapper {
public static void main(String[] args) throws Exception
{
Simple s = new Simple();
//s.mePublic();
Method[] m = Class.forName("com.rixon.scjp.samples.Simple").getDeclaredMethods(); //Simple.class.getMethod("mePublic",);
for(Method m1:m)
{
System.out.println(m1.getName());
if (m1.getName().equals("mePrivate"))
{
try {
AccessibleObject[] a = {m1};
AccessibleObject.setAccessible(a,true);
System.out.println("invoking");
Object[] o = new Object[]{};
m1.invoke(s,o);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}


Simple.java
========
package com.rixon.scjp.samples;

public class Simple {
Simple()
{
System.out.println("hello");
}
public void mePublic()
{
System.out.println("public");
}

private void mePrivate()
{
System.out.println("private");
}
}

No comments: