Kkk.
Kkk.

Reputation: 1

Java Object Set value for field by field name

I have a object this look like:

public class RM {
    private int id;
    private String name;
    private String being_in_force_dt;
    private String modify_dt;
    private AREA AREA;
    private String vehicle;
}

A date from this object I have in xml and now I have a probleme how I can put a value to field for example name , when I have a :

String attName = xpp.getAttributeName(i); // here String = name
xpp.getAttributeValue(i) // and here is a value

I did this :

  if(attName.equals("id"))
                                rm.setId(Integer.parseInt(xpp.getAttributeValue(i)));

But maybe is better soluttion

Upvotes: 0

Views: 6106

Answers (2)

David Geirola
David Geirola

Reputation: 632

You can use Java Reflection, is not a beautiful solution but works:

    RM obj = new RM();
    Field f = obj.getClass().getDeclaredField("id");
    f.setAccessible(true);
    f.set(obj, 1);

    Assert.assertEquals(1, obj.getId());

I suggest you to read about JAXB.

Upvotes: 1

domsson
domsson

Reputation: 4681

One possible solution is to use a HashMap for your attributes.
Not exactly the most versatile approach, but certainly very easy to implement:

public class RM {
    private HashMap<String, String> attributes = new HashMap<>();

    public void setAttribute(String attr, String val) {
        attributes.put(attr, val);
    }

    public String getAttribute(String attr) {
        attributes.get(attr);
    }
}

And then later on:

rm = new RM();
rm.setAttribute(xpp.getAttributeName(i), xpp.getAttributeValue(i));

However, this will use String for all values. This might be okay, as you probably get strings from XML anyway. It would then be up to the user of the RM class to decide what to do with the values retrieved via getAttribute().

Upvotes: 1

Related Questions