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

查看:20
本文介绍了动态查找代表原始 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 实例背部.有没有办法使用该方法或其他方法来取回原始类型类?

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,其中包含名称的静态方法.此方法可用于您描述的确切目的.

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ávid Horváth 和 Patrick 指出断开的链接.

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

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

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