String className = "com.endpoints.EndPointImpl";
String methodName = "add";
String args = "2,3";
try {
Class<?> clas = Class.forName(className);
Object obj = Class.forName(className).newInstance();
java.lang.reflect.Method method = null;
//Type[] types;
for(java.lang.reflect.Method m :obj.getClass().getMethods())
{
if(m.getName().equals(methodName))
{
method = m;
//types = m.getParameterTypes();
break;
}
}
//java.lang.reflect.Method method = clas.getDeclaredMethod(methodName,t);
Object[] strarr = args.split(",");
Object retobj = method.invoke(obj,strarr );
how to i pass arguments to invoke as of now it is generating exception i know why but how can i pass two int
add(in,int)
PS
ArrayList<Object> objArr = new ArrayList<Object>();
for(java.lang.reflect.Method m :obj.getClass().getMethods())
{
if(m.getName().equals(methodName))
{
method = m;
int index = 0;
for(Type type :m.getGenericParameterTypes())
{
if(type.getClass().equals("Integer"))
{
objArr.add(Integer.parseInt(strarr[index]));
}
else if(type.getClass().equals("Float"))
{
objArr.add(Float.parseFloat(strarr[index]));
}
index++;
}
and then pass the objArr in invoke or there is a better solution, i want to also ask if it is possible to create a generic convert function so that it will conver the string to specified type
When writing code, you should always ask yourself what you should be doing. The best way to answer this is to read the Javadoc. Also, please always provide full stacktraces when you get exceptions. You don't need your whole for
loop.
Use Method#getDeclaredMethod(String, Class[])
. It accepts two arguments
name - the name of the method
parameterTypes - the parameter array
If the method is named add
and accepts two int
arguments, call it like this
java.lang.reflect.Method method = clas.getDeclaredMethod("add", int.class, int.class);
The int.class
arguments are the type of parameters the method takes.
You can invoke the method with
method.invoke(object, 3, 3);
where object is an instance of the class declaring add(int, int)
method. If this method is static
, you could pass null
instead. The two 3
s are the int
argument values you would pass as if you were calling the method directly.
object.add(3,3);
If you are receiving Strings to pass in as arguments, you need to cast them first
String args = "2,3";
String[] strarr = args.split(",");
// with no other validation
int[] values = new int[strarr.length];
for (int i = 0; i < strarr.length; i++) {
values[i] = Integer.parseInt(strarr[i]);
}
method.invoke(object, values);
Obviously, perform the appropriate validation when splitting and parsing the Strings.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.