在Java中获得最合适的实例方法 [英] Getting the best fit Instance Method in Java

查看:75
本文介绍了在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.

推荐答案

来自

要在类C中查找匹配方法:如果C恰好声明了一个具有指定名称和完全相同的形式的public方法参数类型,即所反映的方法.如果不止一个这样的方法在C中找到,并且这些方法之一的返回类型为比其他任何方法更具体,都反映出该方法;否则,可以选择其中一种方法.

To find a matching method in a class C: If C declares exactly one public method with the specified name and exactly the same formal parameter types, that is the method reflected. If more than one such method is found in C, and one of these methods has a return type that is more specific than any of the others, that method is reflected; otherwise one of the methods is chosen arbitrarily.

(强调我的.)

您要的是让反射为您执行超载分辨率.而且显然不会.如果您确实需要此功能,则可以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中获得最合适的实例方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆