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
-------------------------------------------------------------------------------------------------------------------------

Total Pageviews

Subscribe via Email

Followers


Popular Posts

About Me

My photo

I am a student of BTech Computer Science Engineering from RCCIIT,Kolkata. I am a crazy lover of Java and wants to settle as a Java developer. I have a seven years Java experience with an application developer experience for 2 years. Recently from March 2012 I am a registered S40 app developer for Nokia and has corrected an app of them. I am currently writing blogs to encourage and grow interest in all those who don't know or learning Java.