Gadgets

Thursday, 17 December 2015

Can we access private constructor in other package

How to access private constructor in other package:
Yes we can access by using reflection classes, we can create instance for private constructors.
To get the class.
Class c=Class.forName("test.Test");
To get all the constructors (public, protected, default, private) in the form of array from the class
Constructor con[]=c.getDeclaredConstructors();
con[0] is indicates first constructor, con[1] indicates second constructor and so an
if setAccessible(true) then all the constructors make as public
if setAccessible(false) then we can’t access all the constructors, we access only public constructors(depending on access specifier rules).
To create object for the class
con[0].newInstance(); 
Test.java
========
package test;
public class Test {
               private Test()
               {
                               System.out.println("private constructor...");                              
               }              
}
Client.java
=========
package core;
import java.lang.reflect.Constructor;
public class Client {
               public static void main(String[] arg)
               {
                               try{
                                              //to get the class
                                              Class c=Class.forName("test.Test");
                                              //to access all the constructors in the array form from the class
                                              Constructor con[]=c.getDeclaredConstructors();
                                              //to make constructor as public
                                              con[0].setAccessible(true);
                                              //to create object
                                              con[0].newInstance();
                               }catch(Exception ex){}
               }
}
/*
Output:
private constructor...
*/

No comments:

Post a Comment