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

来源:互联网 发布:怎样打造淘宝店铺爆款 编辑:程序博客网 时间:2024/05/18 14:15

            下面这个例子演示了如何用反射机制调用自身的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 codeClass[] 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 codebyte[] 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";}}





0 0
原创粉丝点击