Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

How do you set the private member in another class? I was working on a Junit test for a class that isn’t usually wired into my Spring context. Since the class wasn’t being constructed by Spring for the test, I didn’t have the advantage of autowiring.

private CoreServiceBean coreServiceBean;
private EzMoneyServiceBean ezMoneyServiceBean;

Apache Commons BeanUtils didn’t work

I tried using Apache Commons BeanUtils to set the private property, but there is a silent return statement if it is truly private member.

try {
    descriptor =
        getPropertyUtils().getPropertyDescriptor(target, name);
    if (descriptor == null) {
        return; // Skip this property setter
} catch (NoSuchMethodException e) {
    return; // Skip this property setter

Java Reflection

I next tried the Java Reflection API. It seems a little clunky, but it did the job without too much work. I performed the following steps:

  • I looked up the private field by name.
  • I set the field as accessible.
  • I set the new value of the field.

Here is what it looks like for one of the fields:

Field coreServiceBeanField = EzMoneyResourceBean.class.getDeclaredField("coreServiceBean");
coreServiceBeanField.set(ezMoneyResourceBean, coreServiceBean);

November 14th, 2017

Posted In: Java, java ninja, Javaninja


Leave a Comment

WP to LinkedIn Auto Publish Powered By :