动态查找表示原始Java类型的类 [英] Dynamically find the class that represents a primitive Java type

查看:104
本文介绍了动态查找表示原始Java类型的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Java中进行一些反射方法调用。这些调用将包含具有基本类型(int,double等)的参数的方法。反复查找方法时指定此类型的方法是int.class,double.class等。

I need to make some reflective method calls in Java. Those calls will include methods that have arguments that are primitive types (int, double, etc.). The way to specify such types when looking up the method reflectively is int.class, double.class, etc.

挑战在于我接受来自外部源的输入这将动态指定类型。因此,我还需要动态地提出这些类引用。想象一个带有分隔文件的方法名列表以及参数类型列表:

The challenge is that I am accepting input from an outside source that will specify the types dynamically. Therefore, I need to come up with these Class references dynamically as well. Imagine a delimited file a list of method names with lists of parameter types:

doSomething int double
doSomethingElse java.lang.String boolean

如果输入类似于 java.lang.String ,我知道我可以使用 Class.forName(java.lang.String)返回该Class实例。有没有办法使用该方法或其他方法来获取原始类型Classes?

If the input was something like java.lang.String, I know I could use Class.forName("java.lang.String") to that Class instance back. Is there any way to use that method, or another, to get the primitive type Classes back?

编辑:
感谢所有受访者。很明显,没有内置的方法来干净地做我想要的,所以我将决定重用Spring框架中的 ClassUtils 类。它似乎包含Class.forName()的替换,它将符合我的要求。

Thanks to all the respondents. It seems clear that there is no built-in way to cleanly do what I want, so I will settle for reusing the ClassUtils class from the Spring framework. It seems to contain a replacement for Class.forName() that will work with my requirements.

推荐答案

Spring框架包含一个实用程序包含 ClassUtils 的课程静态方法forName。此方法可用于您描述的确切目的。

The Spring framework contains a utility class ClassUtils which contains the static method forName. This method can be used for the exact purpose you described.

如果您不喜欢依赖Spring:源代码方法可以找到 e。 G。 此处 在他们的公共存储库中。类源代码在Apache 2.0模型下获得许可。

In case you don’t like to have a dependency on Spring: the source code of the method can be found e. g. here on their public repository. The class source code is licensed under the Apache 2.0 model.

请注意,该算法使用原始类型的硬编码映射。

Note however that the algorithm uses a hard-coded map of primitive types.

编辑:感谢评论员DávidHorváth和Patrick指出断开的链接。

Thanks to commenters Dávid Horváth and Patrick for pointing out the broken link.

这篇关于动态查找表示原始Java类型的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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