首页 > 解决方案 > Java 反射错误:NoSuchMethodException

问题描述

我刚刚阅读了关于反射的文章并决定尝试一下,但我似乎遇到了一个我找不到原因的错误。

我在课堂上得到以下代码:

String hashType = "md5";
Method method = DigestUtils.class.getDeclaredMethod(hashType + "Hex");
String hash = (String) method.invoke("hello");

这段代码应该将散列字符串存储到变量 hash 中,在运行时抛出以下错误:

java.lang.NoSuchMethodException: org.apache.commons.codec.digest.DigestUtils.md5Hex()
        at java.lang.Class.getDeclaredMethod(Unknown Source)
        at stringHasher.stringHasher.hashString(stringHasher.java:37)

根据 API 文档,该方法确实存在:https ://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/digest/DigestUtils.html

除了不明白这个错误的原因是什么之外,我也不明白为什么我需要将该方法的返回值转换为一个字符串,因为 API 声明它返回一个字符串(类型安全不应该掌握在程序员手中在这种情况下,而不是由 eclipse 强制执行?)。

标签: javareflection

解决方案


您应该添加一个参数类型作为getDeclaredMethod. 你应该传递一些东西(更好null)作为调用静态方法的第一个参数。

String hashType = "md5";
Method method = DigestUtils.class.getDeclaredMethod(hashType + "Hex", String.class);
String hash = (String) method.invoke(null, "hello");

对于非静态方法,您可以这样做:

DigestUtils instance = new DigestUtils();
String hash = (String) method.invoke(instance, "hello");

推荐阅读