DirectFieldAccessor is another implementation of ConfigurablePropertyAccessor which can be used to directly setting/getting instance fields.
DirectFieldAccessor supports nested property paths and collection indexed access as well.
Examples
Bean
package com.logicbig.example;
class Person {
private String name;
private int age;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
Using DirectFieldAccessor
package com.logicbig.example;
import org.springframework.beans.DirectFieldAccessor;
public class DirectFieldAccessorExample {
public static void main (String[] args) {
DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(new Person());
fieldAccessor.setPropertyValue("name", "Mike");
fieldAccessor.setPropertyValue("age", "32");
Object person = fieldAccessor.getWrappedInstance();
System.out.println(person);
}
}
OutputPerson{name='Mike', age=32}
Setting nested properties using DirectFieldAccessor
package com.logicbig.example;
import java.util.List;
class PersonGroup {
private String groupName;
private List<Person> personList;
@Override
public String toString() {
return "PersonGroup{" +
"groupName='" + groupName + '\'' +
", personList=" + personList +
'}';
}
}
package com.logicbig.example;
import org.springframework.beans.DirectFieldAccessor;
import java.util.ArrayList;
public class DirectFieldAccessorNestedFieldsExample {
public static void main (String[] args) {
DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(new PersonGroup());
fieldAccessor.setPropertyValue("groupName", "BaseballTeam");
fieldAccessor.setPropertyValue("personList", new ArrayList<>());
fieldAccessor.setPropertyValue("personList[0]", new Person());
fieldAccessor.setPropertyValue("personList[0].name", "Mike");
fieldAccessor.setPropertyValue("personList[0].age", 24);
fieldAccessor.setPropertyValue("personList[1]", new Person());
fieldAccessor.setPropertyValue("personList[1].name", "Raj");
fieldAccessor.setPropertyValue("personList[1].age", 26);
Object personGroup = fieldAccessor.getWrappedInstance();
System.out.println(personGroup);
}
}
OutputPersonGroup{groupName='BaseballTeam', personList=[Person{name='Mike', age=24}, Person{name='Raj', age=26}]}
Example ProjectDependencies and Technologies Used: - spring-context 6.1.2 (Spring Context)
Version Compatibility: 4.2.0.RELEASE - 6.1.2 Version compatibilities of spring-context with this example: Versions in green have been tested.
- JDK 17
- Maven 3.8.1
|