Any solution for Class.getMethod() reflection and autoboxing?

后端 未结 8 1071
一向
一向 2021-02-12 22:16

I want to use

Class.getMethod(String name, Class... parameterTypes)

to find the method I need to invoke with the given parameters, but apparent

8条回答
  •  情歌与酒
    2021-02-12 23:06

    reflection method look up is not as sophisticated as compiler's. I understand why you need something like that. suppose at runtime you have a method name, and an array of objects as arguments, and you want reflection to give you the exact method based on types of the arguments, but it's more complicated than that. for example:

    void f(Integer i){..}
    void f(int i){...}
    

    when the argument is type Integer, which one can you choose? An even trickier one:

    void f(Integer i, List l){...}
    void f(Object o, LinkedList l){...}
    

    compiler has a set of rules to choose the "most specific method" based on static information; if it can't determine it will alert you right away.

    you have to simulate the compiler and write an algorithm to find out the "most specific method". (oh, and with consideration of auto-boxing, almost forgot that!)

提交回复
热议问题