package com.facade;
import java.lang.reflect.Method;
import com.sun.beans.ObjectHandler;
/**
* 加载门面
*
* @author
*/
public class LoadFacade
{
/**
* 根据对象、方法、参数列表,返回结果
*
* @param obj 对象
* @param methodName 方法名称
* @param params 参数列表
* @return 返回结果
*/
public static Object invoke(Object obj, String methodName, Object[] params)
{
Object resultObj = null;
Method[] methods = obj.getClass().getMethods();
for (Method method : methods)
{
// 判断方法名称和参数列表是否一致
if (method.getName().equals(methodName) && getOverLoader(method.getParameterTypes(), params))
{
try
{
resultObj = method.invoke(obj, params);
break;
}
catch (Exception e)
{
// 什么都不处理(异常丢弃)
}
}
}
return resultObj;
}
/**
* 判断参数列表是否一致
*
* @param paramTypes 参数类型
* @param params 变量类型
* @return 参数列表一致性
*/
private static boolean getOverLoader(Class<?>[] paramTypes, Object[] params)
{
boolean flag = true;
// 无参数
if (null == paramTypes && null == params)
{
return flag;
}
// 参数个数不一致
if (null == paramTypes && null != params || null != paramTypes && null == params
|| paramTypes.length != params.length)
{
flag = false;
return flag;
}
// 参数类型是否一致
int size = paramTypes.length;
for (int index = 0; index < size; index++)
{
// 基本类型需要包装
if (paramTypes[index].isPrimitive())
{
paramTypes[index] = ObjectHandler.typeNameToClass(paramTypes[index].getName());
}
// 参数类型不相同
if (!paramTypes[index].getSimpleName().equals(params[index].getClass().getSimpleName()))
{
flag = false;
break;
}
}
return flag;
}
}
方法调用(设计模式之门面模式)
猜你喜欢
转载自spacecity.iteye.com/blog/1465272
今日推荐
周排行