Monday, June 4, 2012

how to invoke private methods of a class, from outside of that class


package com.yagapp.phaseone;


public class Target {


private void Prin()
{
System.out.println("this is private");
}

private static void prn(){
System.out.println("this is static private");
}
}

***************************************************
package com.yagapp.phaseone;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


import java.lang.reflect.Modifier;


public class PrivateAccess {

/**
* @param args
*/
public static void main(String[] args) {
Class c = Target.class;
Method[] methodes = c.getDeclaredMethods();
for(Method m : methodes)
{
String methodename = m.getName();
m.setAccessible(true);
if(Modifier.isPrivate(m.getModifiers()))
{
if(Modifier.isStatic(m.getModifiers()))
{
try {
m.invoke(c, new Object[]{});
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
try {
m.invoke(new Target(), new Object[]{});
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

}

}

No comments:

Post a Comment