Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the best fit Instance Method in Java

If I run the following program:

class Runit{
    public static void main(String[] argsWut) throws Exception {
        String arg = "what?";
        Class[] parameters = { new Object().getClass() };
        Object[] args = { arg };
        System.out.println("".getClass().getMethod("equals",parameters).invoke("what?",args));
    }
};

I get the following on the command line:

true

On the other hand, if I modify the parameters line a little:

class Runit{
    public static void main(String[] argsWut) throws Exception {
        String arg = "what?";
        Class[] parameters = { arg.getClass() }; // changed a little here so it's a bit more dynamic --
        Object[] args = { arg };
        System.out.println("".getClass().getMethod("equals",parameters).invoke("what?",args));
    }
};

I get:

Exception in thread "main" java.lang.NoSuchMethodException: java.lang.String.equals(java.lang.String)
    at java.lang.Class.getMethod(Class.java:1605)
    at test.Runit.main(Runit.java:7)

From this one example it looks to me as though the getMethod method only works with exact parameters. Is there a way to get some form of a "best fit" method? e.g. If an exact match exists, it would return that method, but if no exact match exists, it can return any method that could accept my given arguments.

like image 735
math4tots Avatar asked Dec 05 '25 19:12

math4tots


2 Answers

You may have better luck with the Apache Commons Lang MethodUtils class, which has a method "invokeMethod" that uses the target arguments for the method to narrow down the appropriate type (i.e., you don't have to tell it the parameter type).

This seems to work:

 System.out.println(MethodUtils.invokeMethod("what?", "equals", new Object[] {"what?"}));

See javadocs for more details: http://commons.apache.org/lang/api/org/apache/commons/lang3/reflect/MethodUtils.html#invokeMethod(java.lang.Object,%20java.lang.String,%20java.lang.Object...)

like image 137
Paul Cichonski Avatar answered Dec 08 '25 08:12

Paul Cichonski


You may be interested in Commons BeanUtils Apache library, specifically this method: http://commons.apache.org/beanutils/v1.8.0/apidocs/org/apache/commons/beanutils/MethodUtils.html#getMatchingAccessibleMethod%28java.lang.Class,%20java.lang.String,%20java.lang.Class%5b%5d%29

Hope this helps

like image 31
Yuriy Nakonechnyy Avatar answered Dec 08 '25 09:12

Yuriy Nakonechnyy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!