Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java / JPA - dynamically setting properties on an object / entity

I'm relatively new to Java and would appreciate any help on this!

I have an XML file full of products like this:

<product>
    <title>Product Title</title>
    <colour>Red</colour>
</product>

And I have a JPA Entity like this:

@Entity
public Product extends Model {

    public String title;
    public String colour;

}

And I can happily parse the XML into my JPA object like this:

public void parseElement(String elementName, String elementValue) {
    if (elementName == "title") {
        product.title = elementValue;
    }
    else if (elementName == "colour") {
        product.colour = elementValue;
    }
}

However the problem is that there are over 50 fields per product, not just the two. I could write a 50+ clause if-else statement, but thought it'd be worth checking here for better alternatives first!

As the XML element names directly match to the property names in the Product class, I thought something like this would be perfect:

public void parseElement(String elementName, String elementValue) {
    product[elementName] = elementValue;
}

But Java doesn't like that notation. Is there something else I can do that would achieve a similar result, or do I have to suck it up and write a collosal if-else statement?

Any help would be greatly appreciated.

Cheers!

like image 724
Chris Waugh Avatar asked Jul 10 '26 13:07

Chris Waugh


2 Answers

Java knows a lot frameworks for XML processing. Also some libs for serializing/deserializing objects to/from xml. I would recommend to have a look at JAXB.

like image 191
magomi Avatar answered Jul 13 '26 22:07

magomi


You'll have to use reflection (error handling ommitted).

product.getClass().getDeclaredField(elementName).set(product, elementValue);

But I stand by others who have suggested XStream. It's a much cleaner way to parse XML files.

like image 23
adarshr Avatar answered Jul 14 '26 00:07

adarshr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!