gpt4 book ai didi

java - 如何干运行 Method.invoke()

转载 作者:太空宇宙 更新时间:2023-11-04 07:24:56 25 4
gpt4 key购买 nike

java.lang.reflect.Method.invoke() 文档指出它抛出 IllegalArgumentException

IllegalArgumentException - if the method is an instance method and the specified object argument is not an instance of the class or interface declaring the underlying method (or of a subclass or implementor thereof); if the number of actual and formal parameters differ; if an unwrapping conversion for primitive arguments fails; or if, after possible unwrapping, a parameter value cannot be converted to the corresponding formal parameter type by a method invocation conversion.

有没有办法测试方法是否在不调用给定参数的情况下抛出 IllegalArgumentException

最佳答案

可以手动检查实例、方法和参数数量的正确性,并通过搭载 native java 机制来检查参数的可分配性。

public class Methods {
public static boolean isInvocable(Method method, Object instance,
Object... arguments) {
return correctInstance(instance, method)
&& correctArguments(arguments, method);
}

private static boolean correctInstance(Object instance, Method method) {
return Modifier.isStatic(method.getModifiers())
|| method.getDeclaringClass().isInstance(instance);
}

private static boolean correctArguments(Object[] arguments, Method method) {
Class<?>[] parameters = method.getParameterTypes();
if (parameters.length != arguments.length) {
return false;
}
for (int i = 0; i < parameters.length; i++) {
if (!correctArgument(arguments[i], parameters[i])) {
return false;
}
}
return true;
}

private static boolean correctArgument(Object instance, Class<?> type) {
return type.isPrimitive()
? correctPrimitive(instance, type)
: instance == null || type.isAssignableFrom(instance.getClass());
}

private static boolean correctPrimitive(Object argument, Class<?> type) {
try {
Method method = Overloading.class.getDeclaredMethod("method", type);
method.setAccessible(true);
method.invoke(null, argument);
return true;
} catch (IllegalArgumentException e) {
return false;
} catch (NoSuchMethodException e) {
throw new Error(e);
} catch (IllegalAccessException e) {
throw new Error(e);
} catch (InvocationTargetException e) {
throw new Error(e);
}
}

@SuppressWarnings("unused")
private static class Overloading {
private static void method(byte argument) {}

private static void method(short argument) {}

private static void method(int argument) {}

private static void method(long argument) {}

private static void method(float argument) {}

private static void method(double argument) {}

private static void method(boolean argument) {}

private static void method(char argument) {}
}
}

关于java - 如何干运行 Method.invoke(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18684337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com