I’m working in a Java framework which is trying to model a Cobol system. I have a class StudentRecord with many attributes.
class StudentRecord extend BaseRecord {
...
public CobolString firstName;
public CobolString lastName;
...
}
class CobolString {
...
private String content;
public setValue(String str){
content = str;
}
}
Let say I have an instanse studentA of type StudentRecord with firstName value in String is ‘Max’. I want to update attribute firstName to ‘John’ using Java reflection. Normally, I do it as below:
Class aClass = studentA.class;
Field field = aClass.getField("firstName");
field.set(studentA, new CobolString("John"));
Because this framework is to model Cobol, it have some weird behaviors and requirements. One of these is that I need to use method setValue() of CobolString to set new value for firstName to be assured that the system works.
For example: without reflection, it require me to do:
studentA.firstName.setValue("John");
With reflection, if I code that way, studentA still has new firstName, but it become a stranger to other object/method and cant work with others!!!
So how can I do the same thing using Java reflection to set new value for firstName. I mean how I get sub object firstName from parent object studentA and then invoke method “setValue” on it with new value “John”.
Thanks for help.
You can access the fields of an instance using reflection:
If the field is
private, execute this before callingField.get():