如何使用反射获取参数类型?
我想使用具有不同数量参数的函数。问题是我不知道每个函数的参数数量,也不知道函数的名称,因为它们存储在数组中。我只知道类名,但不想使用 getDeclaredMethods,因为它会增加搜索时间。有没有办法获取每个函数的参数类型?
I want to use functions having different numbers of parameters. The problem is that I don't know the number of parameters of each function, and also I don't know names of function as they are stored in an array. I only knows the class name, but don't want to use getDeclaredMethods
as it will increase search time. Is there a way to get the parameter types for each function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当我必须查找方法时,我通常所做的就是从我正在执行的查询中生成一个缓存键,并将搜索结果与此缓存键保存在地图中。
示例:
我知道方法参数是
Boolean.TRUE
、Arrays.asList("foo","bar","baz")
和BigInteger.valueOf( 77777l)
我的类包含一个带有签名的方法
我无法直接将参数映射到参数类型,因为我只是不知道哪个超类或接口是参数类型,如您所见下表:
每一对都是兼容的,但是如果不定义比较方法,就无法找到兼容的方法,如下所示:
所以我要做的是有一个方法缓存:
并添加一个像这样的查找方法:
这样,后续查找将比第一次查找花费的时间少得多(对于相同类型的参数)。
当然,由于
Class.getDeclaredMethods()
在内部使用缓存,问题是我的缓存是否能提高性能。这基本上是一个更快的问题:我的猜测:对于大型类(许多方法),第一个方法将获胜,否则第二个方法将获胜
What I usually do when I have to look up methods is to generate a cache key from the query I am doing and save the search result with this cache key in a map.
Example:
I know the method parameters are
Boolean.TRUE
,Arrays.asList("foo","bar","baz")
andBigInteger.valueOf(77777l)
My class contains a method with the signature
There's no way I can directly map the parameters to the parameter types because I just don't know which of the super classes or interfaces is the parameter type as you can see from the following table:
Each of these pairs is compatible, but there's no way to find the compatible method without defining a comparison method, something like this:
So what I'd do is have a method cache:
and add a lookup method like this:
That way, subsequent lookups will take much less time than the first one (for parameters of the same type).
Of course since
Class.getDeclaredMethods()
uses a cache internally, the question is whether my cache improves performance at all. It's basically a question of what's faster:My guess: for large classes (many methods), the first method will win, otherwise the second will