lundi 26 juillet 2021

Reflect set bean Field

Bean

@Service
public class BeanClass{
    private String myField;
}

use

public static void doSomething(ApplicationContext applicationContext){
    Object bean = applicationContext.getBean("beanClass");
    set(bean, AopUtils.getTargetClass(object).getFields[0], "hello")
}

public static void set(Object bean, Field field, Object value){
    if(bean == null || field == null){throw new RuntimeException();}
    field.setAccessible(true);
    field.set(bean, value);
}

The above throws the Exception

Caused by java.lang.IllegalArgumentException: Can not set java.lang.String field my.package.BeanClass.myField to null value

How to set Field of a Spring bean using Reflect?

I can confirm that none of the parameters are null... which shouldnt affect it anyway because I should be able to set an reference types to null.





Aucun commentaire:

Enregistrer un commentaire