工具类
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.reflect.MethodUtils;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class EvolutionMethodUtils extends MethodUtils {
public static Object invokeMethod(final Object object,
final String methodName, Object... args)
throws NoSuchMethodException, IllegalAccessException,
InvocationTargetException {
args = ArrayUtils.nullToEmpty(args);
final Class<?>[] parameterTypes = toClass(args);
return invokeMethod(object, methodName, args, parameterTypes);
}
private static Class<?>[] toClass(final Object... array) {
if (array == null) {
return null;
} else if (array.length == 0) {
return ArrayUtils.EMPTY_CLASS_ARRAY;
}
final Class<?>[] classes = new Class[array.length];
for (int i = 0; i < array.length; i++) {
if (array[i] == null) {
classes[i] = null;
continue;
}
if (array[i] instanceof Integer) {
classes[i] = Integer.TYPE;
} else if (array[i] instanceof Byte) {
classes[i] = Byte.TYPE;
} else if (array[i] instanceof Short) {
classes[i] = Short.TYPE;
} else if (array[i] instanceof Float) {
classes[i] = Float.TYPE;
} else if (array[i] instanceof Double) {
classes[i] = Double.TYPE;
} else if (array[i] instanceof Character) {
classes[i] = Character.TYPE;
} else if (array[i] instanceof Long) {
classes[i] = Long.TYPE;
} else if (array[i] instanceof Boolean) {
classes[i] = Boolean.TYPE;
} else {
classes[i] = array[i].getClass();
}
}
return classes;
}
public static Object forceInvokeMethod(final Object object, String methodName, boolean force) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
return forceInvokeMethod(object, methodName, force, ArrayUtils.EMPTY_OBJECT_ARRAY, null);
}
private static Object forceInvokeMethod(final Object object, final String methodName, boolean force,
Object[] args, Class<?>[] parameterTypes) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
if (!force) {
return invokeMethod(object, methodName, args, parameterTypes);
}
parameterTypes = ArrayUtils.nullToEmpty(parameterTypes);
args = ArrayUtils.nullToEmpty(args);
Class<?> cls = object.getClass();
Method method = null;
try {
method = cls.getDeclaredMethod(methodName, parameterTypes);
} catch (NoSuchMethodException e) {
// ignore
}
if (method == null) {
method = cls.getMethod(methodName, parameterTypes);
}
if (method == null) {
throw new NoSuchMethodException("No such accessible method: "
+ methodName + "() on object: "
+ cls.getName());
}
method.setAccessible(true);
return method.invoke(object, args);
}
}
执行方法调用
// wokeStep方法名称,AbstractCrawler.this 对象实例
EvolutionMethodUtils.forceInvokeMethod(AbstractCrawler.this, workStep, true);