vendredi 20 novembre 2015

Field#set(Object instance, Object obj) seems to only work with static fields

This is not a duplicate since I researched a ton and the only general answer I have found is the set method. Surprisingly, other coders' problems involved the method only having an effect on NON-STATIC variables, where mine is the opposite.

Hello. I am currently practicing reflection and have been working on a mini-library. So far I have developed methods to get field values given a Class object and field name. This works as expected.

However, I am currently in the process of making a method to set fields to a value of type Object given the Class object, the field name and the object to set it to. This does not seem to work with instance variables, only static variables. I am passing in instance of the class rather than the class object into the (Field).get and (Field).set methods, and the get method works flawlessly with static and instance variables. I am seeking an explanation and solution to the problem.

public static void setValueOfField(Class<?> c, String f, Object v) {
    try {
        Field finalField = c.getDeclaredField(f);
        finalField.setAccessible(true);
        final List<Object> parametersCompleteClass = new ArrayList<Object>();
        for (Class<?> parameterType : c.getConstructors()[0].getParameterTypes())
        {
            parametersCompleteClass.add((parameterType.isPrimitive()) ? 0 : null);
        }
        finalField.set(c.getDeclaredConstructors()[0].newInstance(parametersCompleteClass.toArray()), v);
    }
    /* Catches */
}

I am classing this method in my main method as so:

FieldFunctions.setValueOfField(PrivateField.class, "a", 6);

With the field identified as "a" and being located in the PrivateField class as a private variable of primitive type int. Like I said, when I make it static, the set method works as well.

What I have tried:

Making a stalling for loop since there may have been a delay when setting the variable that would have been long enough to not have an effect on the println method. However this is a close-to-useless attempt as the program is syncronous.

What answers I consider:

Should I pass a Class object or an instance of the class into the get and set methods?

Thank you for your time reading this question.

Regards,





Aucun commentaire:

Enregistrer un commentaire