Reflection In Java

3 ways to get the instance of "Class"
1-  .class   -- used with class name or can be used with primitive like int.class

2- forName() - method of Class "Class" -- pass the string which is name of class -- string contains the fully qualified class name

3- getClass() - method from object class -- we have an object obj now we call obj.getClass() to get object of Class

Now from the class object how will you get the instance of the class
public T newInstance()throws InstantiationException,IllegalAccessException - -it is used to create the new instance of the class from Class reference variable


How to access the private menber of the class
1-public void setAccessible(boolean status) throws SecurityException
2-public Object invoke(Object method, Object... args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException is used to invoke the method.

 3-public Method getDeclaredMethod(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.


Now lets have an example for this explanation 
public class A {
  private void message(){System.out.println("hello java"); }
}
File: MethodCall.java
import java.lang.reflect.Method;
public class MethodCall{
public static void main(String[] args)throws Exception{

    Class c = Class.forName("A");
    Object o= c.newInstance();
    Method m =c.getDeclaredMethod("message", null);
    m.setAccessible(true);
    m.invoke(o, null);
}
}

to call  Parameterized method
private void cube(int n){System.out.println(n*n*n);}


Class c=A.class;
Object obj=c.newInstance();
Method m=c.getDeclaredMethod("cube",new Class[]{int.class});
m.setAccessible(true);
m.invoke(obj,4);



Now in interview-??
1- can you also access the private constructor
yes we can also access the private constructor with the same technique as we access the method
Constructor<YourClassName> constructor = YourClassName.class.getDeclaredConstructor(new Class[0]); 
constructor.setAccessible(true)
YourClassName object = constructor.newInstance();


2- How you are going to prevent this     
    a)- if are using this for singleton the Enum is best way to do it.
public static enum BookingFactory {
    INSTANCE;
    public static BookingFactory getInstance() {
        return INSTANCE;
    }
}
 b)- or make the assertion in the constructor
private BookingFactory() {
    if (instance != null)
        throw new IllegalStateException
("Only one instance may be created");
    System.out.println("Object is created.");
}

or use the security manager class
Simple Tutorial

      SecurityManager appsm = System.getSecurityManager();

     appsm.checkPropertyAccess("");

There are many checkxxx method choose your own type

1- How will be access the private fields of class
Field[] allFields = PrivateObject2.class.getDeclaredFields();
            for (Field field : allFields) {
                  // check whether the is private.
                  if (Modifier.isPrivate(field.getModifiers())) {
                        System.out.println(field.getName());
                  }




Comments