Java反射调用具有原始类型的构造函数 [英] Java Reflection calling constructor with primitive types

查看:34
本文介绍了Java反射调用具有原始类型的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的测试框架中有一个方法可以根据传入的参数创建一个类的实例:

I have a method in my test framework that creates an instance of a class, depending on the parameters passed in:

public void test(Object... constructorArgs) throws Exception {
    Constructor<T> con;
    if (constructorArgs.length > 0) {
        Class<?>[] parameterTypes = new Class<?>[constructorArgs.length];
        for (int i = 0; i < constructorArgs.length; i++) {
            parameterTypes[i] = constructorArgs[i].getClass();  
        }
        con = clazz.getConstructor(parameterTypes);
    } else {
        con = clazz.getConstructor();
    }
}

问题是,如果构造函数具有原始类型,这将不起作用,如下所示:

The problem is, this doesn't work if the constructor has primitive types, as follows:

public Range(String name, int lowerBound, int upperBound) { ... }

.test("a", 1, 3);

结果:

java.lang.NoSuchMethodException: Range.<init>(java.lang.String, java.lang.Integer, java.lang.Integer)

原始整数被自动装箱到对象版本中,但如何将它们取回以调用构造函数?

The primitive ints are auto-boxed in to object versions, but how do I get them back for calling the constructor?

推荐答案

使用 Integer.TYPE 而不是 Integer.class.

根据 Javadocs,这是代表原始类型int的Class实例."

As per the Javadocs, this is "The Class instance representing the primitive type int."

您也可以使用 int.class.它是 Integer.TYPE 的快捷方式.不仅是类,甚至对于原始类型,您也可以在 Java 中使用 type.class.

You can also use int.class. It's a shortcut for Integer.TYPE. Not only classes, even for primitive types you can say type.class in Java.

这篇关于Java反射调用具有原始类型的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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