简体   繁体   中英

Java reflection error: NoSuchMethodException

I just read about reflection and decided to give it a try, but I seem to run into an error I can not find the cause for.

I got the following code in a class:

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

This piece of code that should store the hashed string into the variable hash, throws the following error at runtime:

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

According to the API documentation the method does exist: https://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/digest/DigestUtils.html

Beside not understanding what is the cause of this error I also don't understand why I need to cast the returned value by the method to a String as the API states it returns a string (should type safety not be in the hands of the programmer in this case instead of enforced by eclipse?).

You should add an argument type as a second argument in getDeclaredMethod . And you should pass something (better null ) as a first argument to invoke a static method.

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

And for a non-static methods you can do that:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM