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[]里面存储的是一个基本类型还是其对应的包装类?或者这样的思路根本就是有问题的,请提供下其他的思路。