Step 25:Reflection API -22th hour + code

Java-Reflection-Reflection-API[1]
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();

}

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.