I've a list of strings, field names, of a class in a loop from resource bundle. I create an object and then using loop i want to set values for that object. For example, for object
Foo f = new Foo();
with parameter param1, I have string "param1" and I somehow want to concate "set" with it like "set"+"param1" and then apply it on f instance as:
f.setparam1("value");
and same for getter. I know reflection will help but I couldn't manage to do it. Please help. Thanks!
Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value. Given this, getters and setters are also known as accessors and mutators, respectively.
Getter returns the value (accessors), it returns the value of data type int, String, double, float, etc. For the program's convenience, getter starts with the word “get” followed by the variable name. While Setter sets or updates the value (mutators). It sets the value for any variable used in a class's programs.
It is not necessary to write getter or setter for all private variables. It is just a good practice. But without any public function you can not access the private data(variable) of the class.
Yes, the methods of your class should call the getters and setters. The whole point in writing getters and setters is future proofing. You could make every property a field and directly expose the data to the users of the class.
You can do something like this. You can make this code more generic so that you can use it for looping on fields:
Class aClass = f.getClass();
Class[] paramTypes = new Class[1];
paramTypes[0] = String.class; // get the actual param type
String methodName = "set" + fieldName; // fieldName String
Method m = null;
try {
m = aClass.getMethod(methodName, paramTypes);
} catch (NoSuchMethodException nsme) {
nsme.printStackTrace();
}
try {
String result = (String) m.invoke(f, fieldValue); // field value
System.out.println(result);
} catch (IllegalAccessException iae) {
iae.printStackTrace();
} catch (InvocationTargetException ite) {
ite.printStackTrace();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With