I am trying to write a generic function which will accept an Object parameter. It will parse through the Object fields and if it happens to be a String, then it will search for certain characters and replace it. My proficiency in Java isn’t the greatest, so I am stuck at a place where I don’t know how to replace the String value in the original Object parameter. This is the code:
public Object replaceBeanFields(Object obj) throws IllegalArgumentException, IllegalAccessException {
for (Field field : obj.getClass().getDeclaredFields()) {
field.setAccessible(true);
Object value = null;
value = field.get(obj);
if (value instanceof java.lang.String) {
//I want to replace certain characters in this field and return it as part of obj
System.out.println(value);
}
}
return obj;
}
I would appreciate any pointers that would help. Thanks.
>Solution :
Modify the value according to your requirements (See https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html#replaceAll(java.lang.String,java.lang.String))
And then set the changed value onto the object.
if (value instanceof java.lang.String) {
String newValue = ((String)value).replace(regex, replacement);
field.set(obj, newValue);
}
Your case may be different, but in many cases if you’re having to use reflection, you may be missing a simpler way to do things.