Site icon Narayana Tutorial

Java Reflection API

Classes and Objects interview questions

Java Reflection API

Java Reflection API is a process of modifying or retrieve metadata of a class at run time.

The java.lang.Class class provides methods that can be used to get metadata and change the run time behavior of a class.

The java.lang and java.lang.reflect packages are providing classes for java reflection.

The Java Reflection API is using mainly as follows.

  1. IDE Development (Example: Eclipse, Myeclipse, Netbeans etc…)
  2. Testing Tools
  3. Debugger Tools

How to create Object of java.lang.Class?

There are 3 ways to create the Instance of the Class class

  1. forName() method of Class class
  2. getClass() method of Object class
  3. the .class syntax

forName() method of Class class

Example :

package com.samples;

public class NTutorial{

}

package com.samples;

public class Tutorial{

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

Class c=Class.forName("com.samples.NTutorial");

System.out.println("Class name:"+c.getName());

}

}

Output

Class name:com.samples.NTutorial

getClass() method of Object class

Example :

package com.samples;

public class NTutorial{

}

package com.samples;

public class Tutorial{

public void display(Object obj){

Class cls=obj.getClass();

System.out.println("Class Name:"+cls.getName());

}

public static void main(String args[]) {

NTutorial nt=new NTutorial();

Tutorial t=new Tutorial();

t.display(nt);

}
}

Output

Class Name: NTutorial

the .class syntax

Example :

public class Tutorial{

public static void main(String args[]) {

Class c1=boolean.class;

Class c2=int.class;

Class c3=char.class;

Class c4=double.class;

Class c5=Tutorial.class;

System.out.println(c1.getName());

System.out.println(c2.getName());

System.out.println(c3.getName());

System.out.println(c4.getName());

System.out.println(c5.getName());

 

}
}

Output

boolean
int
char
double
Tutorial