jeudi 25 octobre 2018

IllegalArgumentException when trying to get reference to Field using Reflection

I am trying to loop through many ArrayLists of custom classes with the same code and thought using reflection would make it easier. I am running into an issue when I try to get a reference to each field however. Here is a small representation of the code I am trying to run. (my code is different but the essentials are there):

    import java.lang.reflect.*;
    import java.util.ArrayList;


    public class Stack {

        public ArrayList<Custom1> cust11;
        public ArrayList<Custom1> cust12;
        public ArrayList<Custom1> cust13;
        public ArrayList<Custom2> cust21;
        public ArrayList<Custom2> cust22;
        public ArrayList<Custom2> cust23;
        public static void main(String args[]) {
            Stack stack = new Stack();
        }

        public Stack() {
            cust11 = new ArrayList<Custom1>();
            cust12 = new ArrayList<Custom1>();
            cust13 = new ArrayList<Custom1>();
            cust21 = new ArrayList<Custom2>();
            cust22 = new ArrayList<Custom2>();
            cust23 = new ArrayList<Custom2>();

            doReflect();
        }

        public void doReflect(){
            Field[] fields = this.getClass().getFields();
            for(Field f : fields) {
                if(f.getName().contains("cust1")) {
                    try {
                        ArrayList<Custom1> temp = (ArrayList<Custom1>)f.get(cust11);

                    } catch (IllegalArgumentException | IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    class Custom1{
        public Custom1() {}
    }

    class Custom2{
        public Custom2() {}
    }

When it gets to

ArrayList<Custom1> temp = (ArrayList<Custom1>)f.get(cust11);

I get

java.lang.IllegalArgumentException: Can not set java.util.ArrayList field 
Stack.cust11 to java.util.ArrayList
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source)
at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(Unknown Source)
at sun.reflect.UnsafeObjectFieldAccessorImpl.get(Unknown Source)
at java.lang.reflect.Field.get(Unknown Source)
at Stack.doReflect(Stack.java:33)
at Stack.<init>(Stack.java:25)
at Stack.main(Stack.java:14)

How can I do this?





Aucun commentaire:

Enregistrer un commentaire