jeudi 5 mai 2016

How to create a list of a class by using reflection API

I have an input object in JSON which has a list of objects inside it, e.g. Customer has a list of CustomerInfo. Now I am stuck at how to create it back using Reflection API:

public static void invokeMethod(Object obj, String feildName, Object value) throws NoSuchFieldException, SecurityException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {        
    Field field = obj.getClass().getDeclaredField(feildName);

    field.setAccessible(true);

    String methodName = "set" + feildName.substring(0, 1).toUpperCase()+ feildName.substring(1);
    Type type = field.getGenericType();
    if(type instanceof ParameterizedType){
        ParameterizedType pt = (ParameterizedType) type;
        System.out.println("raw type: " + pt.getRawType());
        System.out.println("owner type: " + pt.getOwnerType());
        System.out.println("actual type args:");
        for (Type t : pt.getActualTypeArguments()) {
            System.out.println("    " + t);

which return me this:

18:38:38,984 INFO  [stdout] (http-/0.0.0.0:8080-2) raw type: interface java.util.List
18:38:40,671 INFO  [stdout] (http-/0.0.0.0:8080-2) owner type: null
18:38:42,896 INFO  [stdout] (http-/0.0.0.0:8080-2) actual type args:
18:38:46,366 INFO  [stdout] (http-/0.0.0.0:8080-2)     class brm.model.facts.CustomerInfo     

Now I don't know how to create a list of customer objects back with it using reflection like setCustomerInfo(List<CustomerInfo> customerInfo) and assign it the value that's coming from front end

I started with

Class<?> setterType = setter.getParameterTypes()[0];

if (List.class.isAssignableFrom(setterType)) {
    val = new List(value.toString());
}

but don't know how to achieve the result.

Can someone give me pointers how to do that.





Aucun commentaire:

Enregistrer un commentaire