dimanche 5 juillet 2015

How to convert Boxed data (Integer, Long) to primitive type automatically

I have problems in conversion between primitive and its Boxed type.

I have two arrays args and objs:

        Class<?>[] args = new Class<?>[len];
        Object[] objs = new Object[len];
        int i = 0;
        for (Field field : original.getClass().getDeclaredFields()) {
            objs[i] = getFieldObject(original, field.getName());
            args[i] = field.getType();
            i++;
        }
        return newCls.getConstructor(args).newInstance(objs);

With these two arrays, I want to create a new instance of a class by retrieving its constructor using Reflection.

This code works in most case except some class members are primitive. For example, the below code

public class CI_Caller1 {
    private int _data;
    private CI_Callee_2 _callee;

    public CI_Caller1(int data, CI_Callee_2 callee){
        _data = data;
        _callee = callee;
    }
}

will result in

args: [int, class test.code.jit.asm.classInline.CI_Callee_2]
objs: [Integer(10), test.code.jit.asm.classInline.CI_Callee_2@7aa35e0f]

Here, the newCls.getConstructor(args) succeeds but the newInstance() fails because the first parameter is expected to be int but the given argument is Integer type.

So how can I fix this problem in my code? Thanks





Aucun commentaire:

Enregistrer un commentaire