【Java】反射初探(invoke)

    最近做服务接口,由于时间比较紧,就在设计上比较取巧(其实也是偷懒),使用了反射机制。关键的设计是:使用者调用接口时,传递命令名称和参数,从而可以得到结果。更明确的说实现目的就是:知道方法(函数)名称和参数值,得到此方法的运行后的值。很明显就是方法反射。

   方法类Methods.java

public class Methods {
	public String one(String a, int b, boolean c) {//if c, hello this number;otherwise hello.
		if(c) {
			return a + " number " + b;
		}
		return a;
	}
}
   反射测试类demo Test.java

public class Test {
	public static void main(String[] args) {
		String[] request = {"one", "hello", "1", "true"};//cmd
		Methods m = new Methods();
		Method[] methods = m.getClass().getMethods();
		Method method = null;
		for (Method temp : methods) {
			if(temp.getName().equals(request[0])) {
				method = temp;
				break;//if the class has many methods that have the same name, you need another treatment.
			}
		}
		Class<?>[] classes = method.getParameterTypes();
		//compare the number of parameters
		if(classes.length != request.length - 1) {
			//TODO
			return;
		}
		//compare the type of parameters 
		Object[] params = new Object[classes.length];
		for (int i = 0; i < params.length; i++) {
			try {
				if(classes[i].equals(int.class)) {
					params[i] = Integer.parseInt(request[i+1]);
				} else if(classes[i].equals(boolean.class)) {
					params[i] = Boolean.parseBoolean(request[i+1]);
				} else {
					params[i] = classes[i].cast(request[i+1]);
				}
			} catch (NumberFormatException e) {
				// TODO: handle exception
			} catch (ClassCastException e) {
				// TODO: handle exception
			}
		}	
		String str = "";
		try {
			str = (String) method.invoke(m, params);
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(str);
		
	}
}

 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zfpigpig

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值