How to Invoke Methods by Name using JAVA reflection

I

imran

hi,

I have a code that invoke methods by name. But in this code it just
invoke int a and int b. How can i modify to invoke another data,
String and Double. Actually i want to design fault injection tools.
Below is the code and can someone help me to solve the above problem.
I welcome with example source code.
Thank you....

import java.lang.reflect.*;

public class method2 {

public int add(int a, int b) //////// the problem here
{
return a + b;
}

public static void main(String args[])
{
try {
Class cls = Class.forName("method2");
Class partypes[] = new Class[2];
partypes[0] = Integer.TYPE;
partypes[1] = Integer.TYPE;
Method meth = cls.getMethod( "add", partypes);
method2 methobj = new method2();
Object arglist[] = new Object[2];
arglist[0] = new Integer(37);
arglist[1] = new Integer(47);
Object retobj = meth.invoke(methobj, arglist);
Integer retval = (Integer)retobj;
System.out.println(retval.intValue());
}
catch (Throwable e) {
System.err.println(e);
}
}
}
 
T

Thomas Fritsch

imran said:
Hi Imran!
I have a code that invoke methods by name. But in this code it just
invoke int a and int b. How can i modify to invoke another data,
String and Double.
By modifying the parameter types and the arguments as needed.
If you want to invoke a method declared as
int gggg(Double d, String s)
then you modify your code below like this:
...
partypes[0] = Double.class;
partypes[1] = String.class;
...
arglist[0] = new Double(37.123);
arglist[1] = "efgebeasqaff";
...
Actually i want to design fault injection tools.
Below is the code and can someone help me to solve the above problem.
I welcome with example source code.
Thank you....

import java.lang.reflect.*;

public class method2 {

public int add(int a, int b) //////// the problem here
{
return a + b;
}

public static void main(String args[])
{
try {
Class cls = Class.forName("method2");
Class partypes[] = new Class[2];
partypes[0] = Integer.TYPE;
partypes[1] = Integer.TYPE;
Method meth = cls.getMethod( "add", partypes);
method2 methobj = new method2();
Object arglist[] = new Object[2];
arglist[0] = new Integer(37);
arglist[1] = new Integer(47);
Object retobj = meth.invoke(methobj, arglist);
Integer retval = (Integer)retobj;
System.out.println(retval.intValue());
}
catch (Throwable e) {
System.err.println(e);
}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top