samedi 26 octobre 2019

Java reflection finding method

I have a problem with finding a method with Java, for example, I have to print a value to System.out via reflection:

public static void print(Object value) {
    Method method = PrintStream.class.getMethod("print", value.getClass());
    method.invoke(System.out, value);
}

It works fine with strings, but when I pass an instance of MyClass, for example, I receive the following error:

java.lang.NoSuchMethodException: java.io.PrintStream.print(MyClass)
    at java.lang.Class.getMethod(Class.java:1786)
    at Test.print(Test.java:20)
    at Test.main(Test.java:15)

I believe that's because Java cannot find the method with the exact signature, but here java.io.PrintStream.print(java.lang.Object) suits well. How can I find a method that suits the following classes, not just has the same signature? The approach should also work for multiple arguments.





Aucun commentaire:

Enregistrer un commentaire