Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 30

Reflection in Java

Know
• What is Reflection
• Where we use reflection
• Use and Misuse of reflection
• Steps in using reflection classes
• Simulating an instanceof operator
• Getting detailed info about a class
• Invoking methods of a class
Be Able To
• Write a reflection class
What is Reflection ?
• Reflection is the feature of Java
programming language through which we
can inspect an executing java program
and get information about a class and its
members.
• This is the technique that JavaBeans
“introspection” mechanism uses to
determine the properties, events and
methods that are supported by the bean.
Where we use Reflection
• Many IDE provide ‘code-assist’ and they use
reflection to get information about the class.
• Many framework API rely reflection.
• Used by application that create documentation
• Used by the application servers, testing tools
etc.
Misuse of reflection
• Don’t use reflections when there are better
alternative.
• This is because
– It makes the application slow
– It is difficult to code read and maintain
code that uses reflection extensively.
import java.util.reflect.*;
public class CheckMethod {

public static void main(String args[])


{ throws ClassNotFoundException
try In java.lang.*
throws SecurityException
{
Class c = Class.forName(args[0]);
Method m[]=c.getDeclaredMethods();
for(int i=0;i<m.length;i++)
System.out.println(m[i].toString());

}
catch(Exception e)
{
System.out.println(e);
}
}
Execute the above program as
java CheckMethod java.util.Stack
Output:
public synchronized java.lang.Object
java.util.Stack.pop()
public java.lang.Object
java.util.Stack.push(java.lang.Object)
public boolean java.util.Stack.empty()
public synchronized java.lang.Object
java.util.Stack.peek()
public synchronized int
java.util.Stack.search(java.lang.Ob
ject)
Steps in using reflection classes
• Step 1:
obtain a java.lang.Class object for the
class that you want to manipulate.
• Step 2:
to call a method such as
getDeclaredMethods
• Step 3:
use the reflection API to manipulate the
information
Simulating instanceof operator
public class CheckInstance {
public static void main(String args[])
{
try {
Class cls = Class.forName(“java.lang.Thread");
boolean b1= cls.isInstance(new B());
System.out.println(b1);
boolean b2 = cls.isInstance(new Thread())

System.out.println(b2);
}
catch (Exception e) {
System.out.println(e);
}
}
}
Getting detailed info about a class
package person;
public class Student {
private String name; Bean class
private int regNo;
private String degreeName;
private int currentSemester;
private static int gRegNo;

Student(String nm, String d)


{
setName(nm);
regNo=generateRegno();
setDegreeName(d);
setCurrentSemester(1);
}
Student(String nm)
{
setName(nm);
regNo=generateRegno();
setCurrentSemester(1);
}

private int generateRegno()


{
gRegNo++;
return gRegNo; Bean class contd…
}
public static int getGRegNo()
{
return gRegNo;
}
public void setName(String name)
{
if(name==null)
System.out.println("Inavlid name");
else
this.name=name;
}

public void setDegreeName(String degreeName)


{
if(degreeName==null)
System.out.println("Inavlid degreename");
else
this.degreeName=degreeName;
} Bean class contd…
public void setCurrentSemester(int
currentSemester)
{
if(currentSemester>0 ||
currentSemester<9)
this.currentSemester=currentSemester;
else
System.out.println("Inavlid semester
number");
}
public String getName()
{ Bean class contd…
return name;
}
public String getDegreeName()
{
return degreeName;
}
public int getCurrentSemester()
{
return currentSemester;
}

public int getRegNo()


{
return regNo;
}

} Bean class ended


The CheckClassDetails class
package person;
import java.lang.reflect.*;

public class CheckClassDetails {


public static void main(String args[]){
try{

Class cl=Class.forName("person.Student");
Method m_list[]=cl.getDeclaredMethods();
Constructor
c_list[]=cl.getDeclaredConstructors();
Field f_list[]=cl.getDeclaredFields();
/*method details*/
System.out.println("########### Method Details
###########################");
for(int i=0;i<m_list.length;i++)
{
Method m_list1=m_list[i];
System.out.println("Method--"+(i+1)+" details");
System.out.println("-------------------");
System.out.println("Method
name="+m_list1.getName());
System.out.println("Method declared in
class="+m_list1.getDeclaringClass());
System.out.println(" ");
System.out.println("Parameter List");
Class param[]=m_list1.getParameterTypes();
for(int j=0;j<param.length;j++)
{
System.out.println("Method parameter #" + j
+ " "+param[j].getCanonicalName());
}
System.out.println(" ");
System.out.println("Exception List");
Class exce[]=m_list1.getExceptionTypes();
for(int j=0;j<exce.length;j++)
{
System.out.println("Method exception #" + j + "
"+exce[j]);
}
System.out.println(" ");
System.out.println("Method return type = "+
m_list1.getReturnType());
System.out.println("----End of method-----
"+(i+1));
System.out.println(" ");
}

/*for constructor*/
System.out.println("###########Constructor
details###########################");
for (int i = 0; i < c_list.length; i++) {
Constructor ct = c_list[i];
System.out.println("Constructor name= " +
ct.getName());
System.out.println("Constructor declared in
class = " +ct.getDeclaringClass());
Class param[] = ct.getParameterTypes();
for (int j = 0; j < param.length; j++)

{ System.out.println("Constr
uctor parameter #" + j + " " + param[j])
}
System.out.println("-----------------");
}
System.out.println(" ");
/*field details*/
System.out.println("############ Field details

####################");
for (int i= 0; i < f_list.length; i++) {
Field fld = f_list[i];
System.out.println("Field name= "
+fld.getName());
System.out.println("Field declared in class = "
+fld.getDeclaringClass());
System.out.println("Field type = " +
fld.getType());
int mod = fld.getModifiers();
System.out.println("Field modifiers = "
+Modifier.toString(mod));

System.out.println("---------------------");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output of the program
##################### Method
details###################
Method--1 details
--------------------
Method name=generateRegno
Method declared in class=class
person.Student
Parameter List
Exception List
Method return type
Method return type = int
----End of method-----1
Method--2 details
--------------------
Method name=getGRegNo
Method declared in class=class
person.Student

Parameter List

Exception List

Method return type


Method return type = int
----End of method-----2
Method--3 details
--------------------
Method name=setDegreeName
Method declared in class=class
person.Student

Parameter List
Method parameter #0 java.lang.String

Exception List

Method return type


Method return type = void
----End of method-----3
And so on. . .
########### Constructor details
#################################
Constructor name= person.Student
Constructor declared in class = class
person.Student
Constructor parameter #0 class
java.lang.String
Constructor parameter #1 class
java.lang.String
---------------------------
Constructor name= person.Student
Constructor declared in class = class
person.Student
Constructor parameter #0 class
java.lang.String
---------------------------
############## Field details
#################################
Field name= name
Field declared in class = class
person.Student
Field type = class java.lang.String
Field modifiers = private
----------------------------
Field name= regNo
Field declared in class = class
person.Student
Field type = int
Field modifiers = private
----------------------------
Field name= degreeName
Field declared in class = class
person.Student
Field type = class java.lang.String
Field modifiers = private
----------------------------
Field name= currentSemester
Field declared in class = class
person.Student
Field type = int
Field modifiers = private
----------------------------
Field name= gRegNo
Field declared in class = class
person.Student
Field type = int
Field modifiers = private static
----------------------------
Invoking method of a class
Let us consider a class Add.

package invokemethod;
public class Add {

/** Creates a new instance of Add */


public int add(int a, int b)
{
return a+b;
}
}
We will invoke the add method using reflection.
Class to invoke method
package invokemethod;
import java.lang.reflect.*;
public class InvokeMethod {

public static void main(String args[])


{
try{
Class cl=Class.forName("invokemethod.Add");
Class p_types[]=new Class[2];
p_types[0]=Integer.TYPE;
p_types[1]=Integer.TYPE;
Method m=cl.getMethod("add",p_types);
Object arg_list[]=new Object[2];
arg_list[0]=new Integer(45);
arg_list[1]=new Integer(88);

Object
retreive=m.invoke(cl.newInstance(),arg_list);
System.out.println(retreive);
}
catch(Exception e)
{
System.out.println(e);
}

}
}
Out put is : 133

You might also like