在Java中获得最合适的实例方法

在Java中获得最合适的实例方法

本文介绍了在Java中获得最合适的实例方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我运行以下程序:

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));
    }
};

我得到:

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)

在这个例子中,我觉得 getMethod 方法仅适用于确切的参数.有没有办法获得某种形式的最合适"方法?例如如果存在完全匹配,它将返回该方法,但是如果不存在完全匹配,则可以返回任何可以接受我给定参数的方法.

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.

推荐答案

来自 getMethod() 的文档:

(强调我的.)

您要的是让反射为您执行超载分辨率.而且显然不会.如果您确实需要此功能,则可以1)放弃使用反射并直接调用该方法,或者2)如果不可能,请在Java中查找用于重载解析的规则(您可以启动此处),请使用 getMethods()确定可用方法,然后手动执行重载解析.我知道很有趣.

What you are asking for is to have reflection perform overload resolution for you. And apparently it won't. If you really need this functionality, you can either 1) give up on using reflection and invoke the method directly, or 2) if that's not possible, look up the rules for overload resolution in Java (you could start here), use getMethods() to determine the available methods, and then perform overload resolution manually. Fun times, I know.

编辑:作为其他 指出,有人已经花时间为您做到这一点.酷!

Edit: As other answerers have pointed out, someone has already taken the time to do that for you. Cool!

这篇关于在Java中获得最合适的实例方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 18:13