反射でパラメータが基本タイプか対応するパッケージクラスかをどのように区別するか
3641 ワード
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[]に格納されている基本タイプと対応するパッケージクラスをどのように区別するかです.あるいはこのような考え方には根本的に問題があるので、他の考え方を提供してください.