如何实例化原始类型的Class类? [英] How to instantiate Class class for a primitive type?

查看:128
本文介绍了如何实例化原始类型的Class类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试这样做但不起作用:

I'm trying to do this, but doesn't work:

public static Class loadIt(String name) throws Throwable {
  return Class.forName(name);
}
assert foo.loadIt("int") == int.class; // exception here

我该如何正确地做到这一点?

How should I do this properly?

推荐答案

你不能,因为原语不是对象。

You can't, because primitives are not objects.

你现在尝试的是什么还没有实例化 - 它正在加载一个类。但你不能为原始人做到这一点。每当获取对象(通过反射,例如 method.getReturnType()),但无法使用 forName()加载它

What you are trying currently though is not yet instantiation - it is loading a class. But you can't do that for primitives. int is indeed the name that is used for int types, whenever their Class object is obtained (via reflection, for example method.getReturnType()), but you can't load it with forName().

参考:反思教程


如果类的完全限定名称可用,则可以使用相应的类获取静态方法Class.forName()。 这不能用于基本类型

实例化基元的解决方案是使用 commons-lang ClassUtils ,它可以获取对应的包装类给定的原语:

A solution to instantiate a primitive is to use commons-lang ClassUtils, which can get the wrapper class corresponding to a given primitive:

if (clazz.isPrimitive() {
    clazz = ClassUtils.primitiveToWrapper(clazz);
}
clazz.newInstance();

请注意,这假设您拥有 Class 表示int类型 - 通过反射或通过文字( int.class )。但它超出了我将使用具有字符串表示形式的用例。您可以使用 forName(java.lang.Integer)代替。

Note that this assumes you have the Class representing the int type - either via reflection, or via the literal (int.class). But it is beyond me what would be the usecase of having a string representation of that. You can use forName("java.lang.Integer") instead.

这篇关于如何实例化原始类型的Class类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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