写类似的东西时
doit(43, 44, "hello");
编译器知道要调用哪个重载方法。当我想通过反射做同样的事情时,我需要自己找出方法是
doit(Integer, double, CharSequence...);
并通过类似的方式获取它
Class[] types = {Integer.class, double.class, CharSequence[].class};
declaringClass.getDeclaredMethod("doit", types);
我想知道是否已经有一些东西可以让我只写
Method m = getMethod(declaringClass, "doit", 43, 44, "hello");
我想知道是否有人已经这样做了,因为 JLS在这方面有点复杂。
实际上,像Phase 1 中那样完全 像编译器一样工作是不可能的编译器只接受没有装箱和拆箱的匹配方法。当从上面调用我假设的 getMethod
时,原语和它们的包装器之间的区别已经丢失(因为通过可变参数传递参数时自动装箱)。这个问题好像无解,先忽略吧。
正如答案中所建议的,BeanUtils.invokeMethod
接近。它应该找到最佳匹配,无论它意味着什么。看着MethodUtils .getMatchingAccessibleMethod
表明
- 它对可变参数一无所知
- 它是不确定的
所以我正在寻找更好的东西。
最佳答案
或者你可以使用 Bean Utils from Apache Commons :
public static Method getAccessibleMethod(
Class clazz,
String methodName,
Class[] parameterTypes)
根据documentation :
Return an accessible method (that is, one that can be invoked via reflection) with given name and parameters. If no such method can be found, return null. This is just a convenient wrapper for getAccessibleMethod(Method method).
Parameters: clazz - get method from this class methodName - get method with this name parameterTypes - with these parameters types
实现获取可访问的方法并在层次结构中向上移动,直到找到与之匹配的方法。
直接调用
为了按照您的要求直接执行调用,您可以从相同的 API 使用此方法:
public static Object invokeExactMethod(
Object object,
String methodName,
Object[] args,
Class[] parameterTypes)
throws
NoSuchMethodException,
IllegalAccessException,
InvocationTargetException
甚至
public static Object invokeExactMethod(
Object object,
String methodName,
Object[] args)
throws
NoSuchMethodException,
IllegalAccessException,
InvocationTargetException
首先使用 getAccessibleMethod
定位方法,然后调用它。
关于java - 如何在 Java 中查找重载的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11765627/