反射中如何区分参数是基本类型还是所对应的包装类


package demo.test;

import java.lang.reflect.Method;

/**
* Java Reflection Cookbook<br/>
* eg:<br/>
*     Reflection r = new Reflection(A.class);<br/>
*     Reflection r = new Reflection("com.ehi.A");<br/>
*/
@SuppressWarnings("unchecked")
public class Reflection {

private Class clazz;

private Object object;

private Reflection() {

}

/**
* construct method
* @param obj
*/
public Reflection(Object obj) {
this.object = obj;
clazz = obj.getClass();
}

/**
* construct method
* @param className
* @throws Exception
*/
public Reflection(String className) throws Exception {
if (className == null)
clazz = null;
else
clazz = Class.forName(className);
this.object = clazz.newInstance();
}

/**
* 根据方法名,参数,查找对应的方法,并执行
*
* @param methodName
* 方法名
* @param args
* 参数
* @return 方法返回值
* @throws Exception
*/
public Object invoke(String methodName, Object[] args)
throws Exception {
Class[] parameterTypes = getParameterTypes(args);
Method method = clazz.getDeclaredMethod(methodName, parameterTypes);
method.setAccessible(true);
return method.invoke(object, args);
}

private Class[] getParameterTypes(Object[] args) throws Exception {
if(args == null){
return null;
}
Class[] parameterTypes = new Class[args.length];
for (int i = 0, j = args.length; i < j; i++) {
if(args[i] instanceof Integer){
parameterTypes[i] = Integer.TYPE;
}else if(args[i] instanceof Byte){
parameterTypes[i] = Byte.TYPE;
}else if(args[i] instanceof Short){
parameterTypes[i] = Short.TYPE;
}else if(args[i] instanceof Float){
parameterTypes[i] = Float.TYPE;
}else if(args[i] instanceof Double){
parameterTypes[i] = Double.TYPE;
}else if(args[i] instanceof Character){
parameterTypes[i] = Character.TYPE;
}else if(args[i] instanceof Long){
parameterTypes[i] = Long.TYPE;
}else if(args[i] instanceof Boolean){
parameterTypes[i] = Boolean.TYPE;
}else{
parameterTypes[i] = args[i].getClass();
}
}
return parameterTypes;
}

public void print(Integer i){
System.out.println("Integer: "+i.intValue());
}

public void print(int i){
System.out.println("int: "+i);
}

public static boolean isWrapClass(Class clz) {
try {
return ((Class) clz.getField("TYPE").get(null)).isPrimitive();
} catch (Exception e) {
return false;
}
}

public static void main(String[] args) throws Exception {
Reflection r = new Reflection(new Reflection());
Object[] obj = new Object[1];
int i = 333;
obj[0] = i;
//Integer I = new Integer(333);
//obj[0] = I;
r.invoke("print", obj);
}
}

invoke要实现的是根据方法名和输入的参数自动查找对应的方法,并执行之。遇到的问题就是如何区分Object[]里面存储的是一个基本类型还是其对应的包装类?或者这样的思路根本就是有问题的,请提供下其他的思路。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值