Close

Spring Framework - DirectFieldAccessor Examples

Spring Framework 

DirectFieldAccessor can be used to read and write fields without setters and getters.

package com.logicbig.example.directfieldAccessor;

import org.springframework.beans.DirectFieldAccessor;

public class DirectFieldAccessorExample {

public static void main (String[] args) {
DirectFieldAccessor a = new DirectFieldAccessor(new LocalBean());
a.setPropertyValue("str", "setting a direct value");
System.out.println(a.getWrappedInstance());
}

private static class LocalBean {
private String str;

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

Output

LocalBean{str='setting a direct value'}




DirectFieldAccessor can be used to read and write fields without setters and getters.

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);
}

}

Output

Person{name='Mike', age=32}
Original Post




DirectFieldAccessor can be used to read and write fields without setters and getters.

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);
}

}

Output

PersonGroup{groupName='BaseballTeam', personList=[Person{name='Mike', age=24}, Person{name='Raj', age=26}]}
Original Post




See Also