java - 自动将数字对象转换为其 native 对象

标签 java reflection

我正在尝试创建一个函数,该函数将调用给定一组参数的类的构造函数 封装 testytest;

import java.lang.reflect.Constructor;

public class MainClass {

    public static <T> T newClass(Class<?> inst, Object ... args){
        @SuppressWarnings("unchecked")
        Constructor<?> [] ctor = (inst.getDeclaredConstructors());
        int argIndex = 0;
        ctorLoop: for(Constructor<?> x : ctor){
            argIndex = 0;
            for(Class<?> s : x.getParameterTypes()){
                if(argIndex > args.length || args[argIndex++].getClass() != s){
                    if(argIndex <= args.length)
                    System.out.println("Param doesnt match : " + args[argIndex-1].getClass() + " with " + s);
                    continue ctorLoop;
                }
            }
            try{
                return (T)x.newInstance(args);
            }catch(Exception e){
                System.err.println("Error in instantiating instance of class : " + inst);
                return null;
            }
        }
        System.err.println("No instance of constructor found for class " + inst);
        return null;
    }

    public static void main(String[] args) {
        System.out.println(newClass(Double.class,5.0));

    }

}

这给了我错误

Param doesnt match : class java.lang.Double with double
Param doesnt match : class java.lang.Double with class java.lang.String
No instance of constructor found for class class java.lang.Double

看线

Param doesnt match : class java.lang.Double with double

有没有一种方法可以本地进行 boolean 匹配,而无需交换每个 native 类型( double 、浮点、长整型、整数等?)的大小写?

最佳答案

包装类中定义了一些常量,这些常量表示基本类型的 Class 对象。对于double,使用Double.TYPE .

The Class instance representing the primitive type double.

这应该与您正在查找的构造函数的假定 double 参数相匹配。

其他基元的其他示例有 Integer.TYPEFloat.TYPEShort.TYPEByte.TYPELong.TYPECharacter.TYPEBoolean.TYPE。甚至还有用于 voidVoid.TYPE

关于java - 自动将数字对象转换为其 native 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27934392/

相关文章:

java - 判断成员类是嵌套的还是内部的?

c# - 使用反射的 .NET 远程处理

c# - 递归遍历对象的属性抛出 StackOverflowException

java - 部署java servlets : how to atomatically do the .类文件复制并重启tomcat

java - 尽管实际和预期相同,但 JUnit 给出 ComparisonFailure

java - 为什么myeclipse控制台没有输出?

java - IzPack 5.0.0 beta 8 + izpack_home

java - JUnit 4.12 : testing util classes

c# - 访问空值会导致应用程序失败/C#

c# - Linq 查询从对象 B 中获取与对象 A 具有相同名称和类型的属性