Sunday, February 16, 2014
Today I will show that how the power of reflection can bypass encapsulation. This is excellent feature in Java. You must have read and experienced that you cannot create instances of class with private constructors using "new" keyword outside that class. But using reflection you can do mit very easily.And using that  we can call any methods and do as we wish. To do that we have to follow these steps :

  1. Create the Class class instance of the specified class using Class.forName() or <Class-Name>.class
  2. Create the Constructor instance from the Class instance using getDeclaredConstructor()
  3. Call the setAccessible() on constructor object and set to true. This is the most important step as failing it wont allow you to access the private constructor.
  4. Call newInstance() method on the constructor object which will return a reference to Object class. That's it. Dow what you wish with this reference.
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
import java.lang.reflect.Constructor;

class PrivateCons {
   private String i;
   private PrivateCons(String i){
    this.i=i;
   }
   @Override
   public String toString(){
    return "I am "+i;
   }
}

public class PrivateConsReflect{
 public static void main(String[] args) throws Exception{
  Class c=PrivateCons.class;  //getting Class class instance
  Constructor cons=c.getDeclaredConstructor(String.class);  //getting constructor
  cons.setAccessible(true);  //setting true to access private feature
  Object pc=cons.newInstance("5");  //creating instance of the class
  System.out.println(pc);  //printing object
 }
}
-------------------------------------------------------------------------------------------------------------------------
Download Links
-------------------------------------------------------------------------------------------------------------------------

0 comments:

Post a Comment

Total Pageviews

Followers


Labels

Popular Posts

free counters