You can access private method from outside class by changing the runtime behavior of the class
public method getDeclareMethod(String name,Class[] parameterTypes) throws NoSuchMethodException,SecurityException : returns a Method object that reflects the specified declared method of the class or interface represented by this Class object.
Result : Test
public method getDeclareMethod(String name,Class[] parameterTypes) throws NoSuchMethodException,SecurityException : returns a Method object that reflects the specified declared method of the class or interface represented by this Class object.
public class DynamicClass { private void show(){ System.out.println("Test"); } } import java.lang.reflect.Method; public class AccessPrivateMethod { public static void main(String args[]){ try{ Class clsClass = Class.forName("DynamicClass"); Object o = clsClass.newInstance(); Method method = clsClass.getDeclaredMethod("show", null); method.setAccessible(true); method.invoke(o, null); }catch(Exception e){ e.printStackTrace(); } } } |
Result : Test
is it Access in constructor ?
ReplyDeletesuppose if i create one constructor and i want to access private method in that so is it work ?
yes, we can access in constructor.
Delete