All Downloads are FREE. Search and download functionalities are using the official Maven repository.
Please wait. This can take some minutes ...
Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance.
Project price only 1 $
You can buy this project and download/modify it how often you want.
net.lulihu.ObjectKit.MethodKit Maven / Gradle / Ivy
package net.lulihu.ObjectKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.reflect.MethodUtils;
import java.lang.reflect.InvocationTargetException;
/**
* 操作方法工具类
*/
@Slf4j
public class MethodKit {
/**
* 对象是否存在指定方法
*
* @param aClass 对象类型
* @param name 方法名称
* @param parameterTypes 方法参数类型
* @return true 存在 反之不存在
*/
public static boolean existSpecifiedMethod(Class> aClass, String name, Class>[] parameterTypes) {
return MethodUtils.getAccessibleMethod(aClass, name, parameterTypes) != null;
}
/**
* 执行目标方法
*
* @param object 目标对象
* @param methodName 目标方法
* @param args 方法参数
* @return 方法执行结果
* @throws NoSuchMethodException 没有这样的方法例外
* @throws IllegalAccessException 非法访问例外
* @throws InvocationTargetException 调用方法执行异常
*/
public static Object invokeExactMethod(Object object, String methodName, Object[] args,
Class>[] parameterTypes)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
return MethodUtils.invokeExactMethod(object, methodName, args, parameterTypes);
}
/**
* 执行目标方法 , 不抛出异常,如果发生异常则返回null,且打印错误信息
*
* @param object 目标对象
* @param methodName 目标方法
* @param args 方法参数
* @return 方法执行结果
*/
public static Object invokeExactMethodNotException(final Object object,
final String methodName,
Object... args) {
try {
args = ArrayUtils.nullToEmpty(args);
final Class>[] parameterTypes = ClassUtils.toClass(args);
return invokeExactMethod(object, methodName, args, parameterTypes);
} catch (NoSuchMethodException e) {
Object[] finalArgs = args;
LogKit.error(log, "【{}】不存在方法【{}({} )】...", () -> new Object[]{object.getClass(), methodName,
StrKit.listStitchingStr(obj -> " " + obj.getClass(), finalArgs), e});
} catch (IllegalAccessException e) {
LogKit.error(log, "【{}】方法【{}】无法通过反射访问...", () -> new Object[]{object.getClass(), methodName, e});
} catch (InvocationTargetException e) {
LogKit.error(log, "【{}】运行方法【{}】时发生例外...", () -> new Object[]{object.getClass(), methodName, e});
}
return null;
}
}