简体   繁体   中英

Set a value in a class with reflection, with the Class, Field and value as parameters in a method

I have this method that is supposed to set a field in the given class to the specified value:

public void setValue(Class<?> instance, String fieldName, Object value) {
    try {
        Field field = instance.getDeclaredField(fieldName);

        field.setAccessible(true);
        field.set(instance, value);
    } catch (NoSuchFieldException e) {
        if (instance.getSuperclass() != null) {
            setValue(instance.getSuperclass(), fieldName, value);
        } else {
            try {
                throw new NoSuchFieldException("Could not find field " + fieldName + " in any class.");
            } catch (NoSuchFieldException ex) {
                ex.printStackTrace();
                e.printStackTrace();
            }
        }
    } catch (SecurityException | IllegalArgumentException | IllegalAccessException exx) {
        exx.printStackTrace();
    }
}

However, it gives this error when I try to set any field:

java.lang.IllegalArgumentException: Can not set float field net.minecraft.server.v1_6_R2.Packet43SetExperience.a to java.lang.Class

I have tried using an Object(instead of an Class) but it never finds the field that I need, it only finds the fields that the Object class has. I also tried using generics, but the same thing happened.

You need to have the actual instance of the object to pass in to the set method , not the Class object itself. Add a parameter to your method to take the actual instance:

public void setValue(Class<?> clazz, Object instance, String fieldName, Object value) {

I renamed the Class<?> parameter clazz for clarity, so it would need to be changed elsewhere:

Field field = clazz.getDeclaredField(fieldName);

And pass the actual instance to set :

field.set(instance, value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM