动态地找到代表原始Java类型的类(Dynamically find the class that represents a primitive Java type)

编程入门 行业动态 更新时间:2024-10-28 03:18:32
动态地找到代表原始Java类型的类(Dynamically find the class that represents a primitive Java type)

我需要在Java中进行一些反射方法调用。 那些调用将包括具有原始类型(int,double等)的参数的方法。 反映方法查找方法时指定这种类型的方法是int.class,double.class等。

挑战在于,我接受外部来源的输入,动态指定类型。 因此,我也需要动态地提出这些类的引用。 想象一下一个分隔的文件列表,其中列出了参数类型的方法名称:

doSomething int double doSomethingElse java.lang.String boolean

如果输入是像java.lang.String这样的东西,我知道我可以使用Class.forName("java.lang.String")到该类的实例。 有没有办法使用该方法或另一种方法来获取原始类型Classes?

编辑:感谢所有受访者。 很明显,没有内置的方式干净地做我想要的,所以我将解决从Spring框架重用ClassUtils类。 它似乎包含一个替代Class.forName()将适用于我的要求。

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

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?

Edit: 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。 该方法可以用于您所描述的确切目的。

如果你不喜欢对Spring有依赖:可以找到方法的源代码 e。 G。 这里是他们的公共仓库。 类源代码是根据Apache 2.0模型许可的。

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


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

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.

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.


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

更多推荐

本文发布于:2023-08-06 10:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1446736.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:原始   类型   代表   动态   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!