Close

Java - Different ways to Set Field Value by Reflection

[Last Updated: Apr 3, 2020]

Java Reflection Java 

This tutorial shows different ways to set field values by using Java Reflection.

Examples

Example POJO

public class Person {
  private String name;

  public String getName() {
      return name;
  }

  public void setName(String name) {
      this.name = name;
  }

  @Override
  public String toString() {
      return "Person{" +
              "name='" + name + '\'' +
              '}';
  }
}

Using java.lang.reflect.Field

package com.logicbig.example;

import java.lang.reflect.Field;

public class JavaFieldExample {
  public static void main(String[] args) throws Exception {
      Person p = new Person();
      System.out.println("before: "+p);
      Field field = Person.class.getDeclaredField("name");
      field.setAccessible(true);
      field.set(p, "Tina");
      field.setAccessible(false);
      System.out.println("after: "+p);
  }
}
before: Person{name='null'}
after: Person{name='Tina'}

Invoking setter via java.lang.reflect.Method

package com.logicbig.example;

import java.lang.reflect.Method;

public class JavaSetterMethodExample {
  public static void main(String[] args) throws Exception {
      Person p = new Person();//must have setter
      System.out.println("before: "+p);
      Method setter = Person.class.getDeclaredMethod("setName", String.class);
      setter.invoke(p, "Tina");
      System.out.println("after: "+p);
  }
}
before: Person{name='null'}
after: Person{name='Tina'}

Using BeanInfo

package com.logicbig.example;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.Arrays;
import java.util.Optional;

public class JavaBeanInfoExample {
  public static void main(String[] args) throws Exception {
      Person p = new Person();//must have getters and setters
      System.out.println("before: " + p);
      BeanInfo beanInfo = Introspector.getBeanInfo(Person.class);
      Optional<PropertyDescriptor> propertyDescriptor = Arrays.stream(beanInfo.getPropertyDescriptors())
                                                              .filter(pd -> pd.getName().equals("name"))
                                                              .findAny();
      if (propertyDescriptor.isPresent()) {
          propertyDescriptor.get().getWriteMethod().invoke(p, "Tina");
          System.out.println("after: " + p);
      }
  }
}
before: Person{name='null'}
after: Person{name='Tina'}

Using Commons BeanUtils

pom.xml

<dependency>
   <groupId>commons-beanutils</groupId>
   <artifactId>commons-beanutils</artifactId>
   <version>1.9.4</version>
</dependency>
package com.logicbig.example;

import org.apache.commons.beanutils.BeanUtils;

public class ApacheCommonBeanUtilsExample {
  public static void main(String[] args) throws Exception {
      Person p = new Person();//must have getters and setters
      System.out.println("before: " + p);
      BeanUtils.setProperty(p, "name", "Tina");
      System.out.println("after: " + p);
  }
}
before: Person{name='null'}
after: Person{name='Tina'}

Using Spring beans

pom.xml

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-beans</artifactId>
   <version>5.2.5.RELEASE</version>
</dependency>

Direct field Access

package com.logicbig.example;

import org.springframework.beans.ConfigurablePropertyAccessor;
import org.springframework.beans.PropertyAccessorFactory;

public class SpringFieldAccessorExample {
  public static void main(String[] args) {
      Person p = new Person();
      System.out.println("before: "+p);
      ConfigurablePropertyAccessor propertyAccessor = PropertyAccessorFactory.forDirectFieldAccess(p);
      propertyAccessor.setPropertyValue("name", "Tina");
      System.out.println("after: "+p);
  }
}
before: Person{name='null'}
after: Person{name='Tina'}

Setter access

package com.logicbig.example;

import org.springframework.beans.ConfigurablePropertyAccessor;
import org.springframework.beans.PropertyAccessorFactory;

public class SpringPropertyAccessorExample {
  public static void main(String[] args) {
      Person p = new Person();//must have getters and setters
      System.out.println("before: " + p);
      ConfigurablePropertyAccessor propertyAccessor = PropertyAccessorFactory.forBeanPropertyAccess(p);
      propertyAccessor.setPropertyValue("name", "Tina");
      System.out.println("after: " + p);
  }
}
before: Person{name='null'}
after: Person{name='Tina'}

Example Project

Dependencies and Technologies Used:

  • commons-beanutils 1.9.4: Apache Commons BeanUtils provides an easy-to-use but flexible wrapper around reflection and introspection.
  • spring-beans 5.2.5.RELEASE: Spring Beans.
  • JDK 8
  • Maven 3.5.4

Java Reflection - setting field value Select All Download
  • java-reflection-setting-field-value
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • ApacheCommonBeanUtilsExample.java

    See Also