FAQ

Java

JSP

Servlet


Advertisement



How to Use Reflection to Call Methods in Java?

You can invoke methods on objects dynamically. First, you must get their definition through one of the methods Class.getMethod(String,Class[]) or Class.getDeclaredMethod(String,Class[]). The first parameter is the method??s name and the second is an array of Class objects representing the types of its parameters.

The getMethod can handle inheritance but only picks up public methods. It returns the public method that matches the parameters provided, whether it is declared by the class or inherited.

 
class Parent {
public long l;
public void setLong(long l) {
this.l = l;
}
}

public class Program extends Parent {

public static void main(String[] args) {

// Get the Class object associated with this class.
Program program = new Program();
Class progClass = program.getClass();

try {
// Get the method named sayHello.
Method helloMethod = progClass.getMethod( "sayHello", null);
System.out.println("Method found: " + helloMethod.toString());
}
catch (NoSuchMethodException ex) {
System.out.println(ex.toString());
}

try {
// Get the method named setStr.
Class[] args1 = {String.class};
Method strMethod = progClass.getMethod( "setStr", args1);
System.out.println("Method found: " + strMethod.toString());
}
catch (NoSuchMethodException ex) {
System.out.println(ex.toString());
}

try {
// Get the method named setDate.
Class[] args2 ={Date.class};
Method dateMethod = progClass.getMethod( "setDate", args2);
System.out.println("Method found: " + dateMethod.toString());

}
catch (NoSuchMethodException ex) {
System.out.println(ex.toString());
}

try {
// Get the method named setI.
Class[] args3 = {Integer.TYPE};
Method iMethod = progClass.getMethod( "setI", args3);
System.out.println("Method found: " + iMethod.toString());
}
catch (NoSuchMethodException ex) {
System.out.println(ex.toString());
}

try {
// Get the method named setI.
Class[] args4 ={Long.TYPE};
Method lMethod = progClass.getMethod( "setLong", args4);
System.out.println("Method found: " + lMethod.toString());
}
catch (NoSuchMethodException ex) {
System.out.println(ex.toString());
}
}

public String sayHello()
{
return "Hello!";
}

public void setStr(String str)
{
this.str = str;
}

private void setDate(Date date)
{
this.date = date;
}

private void setI(int i)
{
this.i = i;
}

public String str = "Hello";
private Date date = new Date();
protected int i = 0;
}

/* Output
Method found: public java.lang.String com.xyzws.Program.sayHello()
Method found: public void com.xyzws.Program.setStr(java.lang.String)
java.lang.NoSuchMethodException: com.xyzws.Program.setDate(java.util.Date)
java.lang.NoSuchMethodException: com.xyzws.Program.setI(int)
Method found: public void com.xyzws.Parent.setLong(long)
*/

The getDeclaredMethod returns all methods including package, protected, and private but exculding inherited methods.

 
class Parent {
public long l;
public void setLong(long l) {
this.l = l;
}
}

public class Program extends Parent {

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

// Get the Class object associated with this class.
Program program = new Program();
Class progClass = program.getClass();

// Get the method named sayHello.
Method helloMethod = progClass.getDeclaredMethod( "sayHello", null);
System.out.println("Method found: " + helloMethod.toString());

// Get the method named setStr.
Class[] args1 = {String.class};
Method strMethod = progClass.getDeclaredMethod( "setStr", args1);
System.out.println("Method found: " + strMethod.toString());

// Get the method named setDate.
Class[] args2 ={Date.class};
Method dateMethod = progClass.getDeclaredMethod( "setDate", args2);
System.out.println("Method found: " + dateMethod.toString());

// Get the method named setI.
Class[] args3 = {Integer.TYPE};
Method iMethod = progClass.getDeclaredMethod( "setI", args3);
System.out.println("Method found: " + iMethod.toString());

// Get the method named setI.
Class[] args4 ={Long.TYPE};
Method lMethod = progClass.getDeclaredMethod( "setLong", args4);
System.out.println("Method found: " + lMethod.toString());
}
catch (NoSuchMethodException ex) {
System.out.println(ex.toString());
}
}

public String sayHello()
{
return "Hello!";
}

public void setStr(String str)
{
this.str = str;
}

private void setDate(Date date)
{
this.date = date;
}

private void setI(int i)
{
this.i = i;
}

public String str = "Hello";
private Date date = new Date();
protected int i = 0;
}

/* Output
Method found: public java.lang.String com.xyzws.Program.sayHello()
Method found: public void com.xyzws.Program.setStr(java.lang.String)
Method found: private void com.xyzws.Program.setDate(java.util.Date)
Method found: private void com.xyzws.Program.setI(int)
java.lang.NoSuchMethodException: com.xyzws.Program.setLong(long)
*/

Reflection is used to invoke a method when name of the method is supplied at run time. The method??s definition is represented by an instance of the java.lang.reflect.Method class. Using its API you can get any information you want about the method it represents. You can also invoke the method on an object using Method.invoke(Object,Object[]). The first argument is the object whose method you want to call (ignored if the method is static). The second is an array of objects corresponding to the parameters to be passed to the method that is invoked. If the parameter is a primitive type, the corresponding value in the argument array must be the appropriate wrapper object

package com.xyzws;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;

class Sample {
static private int privateInt = 1;
protected float protectedField = 1.2F;
int[] data = { 4, 3, 2, 1 };
public String message = "Hi world!";

public Sample() {
System.out.println( "Default Constructor" );
}

public Sample( String newMessage ) {
System.out.println( "One arg Constructor" );
message = newMessage;
}

public final void setData( int[] newData ) {
System.out.println( "Set data" );
data = newData;
}

public void setFields( int anInt, float aFloat,
String aMessage ) {
System.out.println( "Set fields" );
privateInt = anInt;
protectedField = aFloat;
message = aMessage;
}

public String toString() {
StringBuffer str = new StringBuffer();
str.append("[");
for (int i: data) {
str.append(i).append(" ");
}
str.append("]");
return "Sample(" + privateInt + ", " +
protectedField + ", " +
message + ", " + str.toString() +")";
}
}

public class Program
{
public static void main(String[] args)
throws SecurityException,
NoSuchMethodException,
InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException
{
Class clz = Sample.class;
Class[] argumentTypes = { int.class, float.class, String.class };
Method setFields = clz.getMethod( "setFields", argumentTypes);

Class[] argumentTypes1 = { int[].class };
Method setData = clz.getMethod( "setData", argumentTypes1);

Object aSample = clz.newInstance();
System.out.println( aSample );

Object[] arguments = { new Integer(23), new Float(100.35f), "Bye" };
setFields.invoke( aSample, arguments );
System.out.println( aSample );



Constructor oneArgument = clz.getConstructor(java.lang.String.class);
Object newObject = oneArgument.newInstance(
new Object[]{"Hi xyzws!" } );
System.out.println( newObject );
int[] someData = { 1, 2, 3, 4 };
Object[] arguments1 = { someData };
setData.invoke( newObject, arguments1 );
System.out.println( newObject );

}
}

/* output
Default Constructor
Sample(1, 1.2, Hi world!, [4 3 2 1 ])
Set fields
Sample(23, 100.35, Bye, [4 3 2 1 ])
One arg Constructor
Sample(23, 1.2, Hi xyzws!, [4 3 2 1 ])
Set data
Sample(23, 1.2, Hi xyzws!, [1 2 3 4 ])
*/


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |