lundi 13 août 2018

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?).





Aucun commentaire:

Enregistrer un commentaire