java - 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 强制执行?)。
解决方案
您应该添加一个参数类型作为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");
推荐阅读
- angularjs - 在 AngularJS 中向 ng-patterns 添加两个模式时出错
- mysql - MySQL 每月/每年重复事件
- batch-file - 使用批处理脚本在字符串中插入字符
- java - 打开 CV 相机错误 - 初始化期间绿色闪烁
- vue.js - 隐藏或混淆 webpack 块文件的真实路径名
- django - /accounts/password_reset/ 处的 NoReverseMatch
- python - Python mysql.connector rowcount > 0 但 fetchall() 没有显示结果
- typescript - 从类型化函数中提取接口/类型
- javascript - 无法升级到 React-Bootstrap 最新版本
- eclipse - Eclipse CDT 插件 - 检索引用的 CDTName 值 - 函数体和常量值