How to access a field via java Reflection in a Spring Cglib extended class?

Viewed 109

So I have a Spring Application and im using a bean post processor. This is my code:

@Component
public class TestProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        var annotation = AnnotationUtils.findAnnotation(bean.getClass(), RestController.class);
        if (annotation != null) {
            System.out.println("IM HERE");
            var clazz = bean.getClass();
            if (UserController.class.isAssignableFrom(clazz)) {
                try {
                    var srcClass = bean.getClass().getSuperclass();
                    var f = srcClass.getDeclaredField("service");
                    var obj = f.get(bean);
                    System.out.println(obj);
                } catch (IllegalArgumentException | NoSuchFieldException | SecurityException | IllegalAccessException e) {
                    e.printStackTrace();
                }
            }

            return bean;
        }
        return bean;
    }
}

Now I need to access the the UserService variable in the controller. I know it is present and defined because I used a @PostConstruct to print it and it is there (yes it prints before the processor hence the "IM HERE" print). Despite this, and the bean being defined, when i try to get it via reflection, it comes null. Now I know that the class im analyzing isnt exacly my controller, it is a UserController$$EnhancerBySpringCGLIB... type thing. So my question is, if i want to access that variable, how do I do it?

0 Answers
Related