Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace string values from any Object class – Java

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading