Definition-

Generally reflection means -Ability of a software to analyze itself.
In java, reflection api allows to analyze and modify runtime behavior of class, at runtime.

Let’s take a class Abc to analyze with reflection api


package reflexn;

public class Abc {

private int age=12;
public String name="asd";

public Abc() {
System.out.println("asdfgh");
}

private Abc(String a){
System.out.println("zxcmnb");
}

public void ds(){
System.out.println("dfg");
}

private void sd(){
System.out.println("asd");
}
}

package- java.lang.reflect

Some important classes –
1- Class – this class is used to load any class dynamically.


package reflexn;

public class Cls {

public static void main(String[] args) throws ClassNotFoundException {
Class c = Class.forName("rexn.Abc");
}

}

2- Constructor


package reflexn;

import java.lang.reflect.*;
import java.util.Arrays;

public class Const {
public static void main(String args[]) throws ClassNotFoundException {

Class c = Class.forName("reflexn.Abc");
Constructor[] cdt = c.getDeclaredConstructors();
System.out.println(Arrays.toString(cdt));
}
}

3- Method-


package reflexn;

import java.lang.reflect.*;
import java.util.Arrays;

public class Methds {
public static void main(String args[]) throws ClassNotFoundException {

Class c = Class.forName("reflexn.Abc");

Method md[] = c.getDeclaredMethods();
System.out.println(Arrays.toString(md));
}
}

4- Fields-


package reflexn;
import java.lang.reflect.*;
import java.util.Arrays;

public class Flds
{
public static void main(String args[]) throws ClassNotFoundException {
Class c = Class.forName("reflexn.Abc");
Field f[] = c.getDeclaredFields();
System.out.println(Arrays.toString(f));
}
}

*Object creation using newInstance method


package reflexn;

public class Nwins {
public static void main(String args[])
throws ClassNotFoundException, InstantiationException, IllegalAccessException {

Class c = Class.forName("reflexn.Abc");

Abc a = (Abc) c.newInstance();
}
}

Advertisements