您的位置:首页 > 编程语言 > Java开发

用java的反射机制执行某个方法并传递复杂参数

2014-04-18 08:15 423 查看
下面这个例子演示了如何用反射机制调用自身的multiParametersTest方法并传递复杂的函数。

get method code那段,是照着multiParametersTest的各个参数类型去填argTypes,然后根据方法名和argTypes参数类型去找定位这个类的方法。而invoke有两个参数,一个是instance(实例),如果要运行static方法,这个参数要设为null;另一个参数是Object[],这个是执行这个方法时传递的参数,它每一个元素的数据类型一定要跟argTypes和方法本身的参数类型保持一致。

package com.dgmislrh.eclassloader.test;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test {

/**
* @param args
* @throws ClassNotFoundException
* @throws InstantiationException
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws NoSuchMethodException
* @throws SecurityException
*/
public static void main(String[] args) throws ClassNotFoundException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException, SecurityException, NoSuchMethodException {
// TODO Auto-generated method stub
//System.out.println("this is main entry.");
Class<?> c = Class.forName(Test.class.getName());
//get method code
Class[] argTypes=new Class[4];
argTypes[0]=byte[].class;
argTypes[1]=int.class;
argTypes[2]=int.class;
argTypes[3]=String.class;
Method m=c.getDeclaredMethod("multiParametersTest",argTypes);
//invode code
byte[] bytes=new byte[3];
bytes[0]=1;
bytes[1]=2;
bytes[2]=3;
m.invoke(c.newInstance(), new Object[]{bytes,100,200,"hello"});
}
public static void sayHello(String name){
System.out.println("Hello,"+name);
}
public String getMyName(String xing){
return "My Name is :"+xing;
}
public String getMyNames(String[] xing){
return "My Name is :"+xing[0]+(xing.length>1?","+xing[1]:"");
}
public String multiParametersTest(byte[] bytes,int i,int j,String s){
System.out.println(bytes.length);
System.out.println(i);
System.out.println(j);
System.out.println(s);
return "YES";
}
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: