Thursday, January 8, 2009

accessing class private constructor outside class

We can create object of class which has private constructor, outside the class using the Reflection API.
See the code below.
Class with private constructor
package test;
public class privateconstructor implements NewInterface {
private privateconstructor() { }
public void fine() {
System.out.println("fine"); }}Program creating the above class and calling the method
package test;
import java.lang.reflect.Constructor;
public class Main {
public static void main(String[] args) throws Exception {
privateconstructor keyPair;
Class c = privateconstructor.class;
Constructor[] cons = c.getDeclaredConstructors();
cons[0].setAccessible(true);
keyPair = cons[0].newInstance(); keyPair = (privateconstructor) c.newInstance();
keyPair.fine();
}}
You can acess this private variables and private methods using reflection.

1 comment:

  1. using this code not possible to create object for privateconstructor

    IllegalAccessException raised

    ReplyDelete