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

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



 


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值