0

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

Krzysztof Pokrywka
  • 1,356
  • 4
  • 27
  • 50

2 Answers2

1

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

domsson
  • 4,553
  • 2
  • 22
  • 40
1

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.

domsson
  • 4,553
  • 2
  • 22
  • 40
David Geirola
  • 616
  • 3
  • 17
  • You might want to add a link to the [Java Tutorials](http://docs.oracle.com/javase/tutorial/reflect/index.html) or a SO question like [this one](https://stackoverflow.com/questions/37628/what-is-reflection-and-why-is-it-useful) – domsson Jul 13 '17 at 14:00
  • Sure, this is a very simple example: https://www.mkyong.com/java/jaxb-hello-world-example/ In the example annotations are on getter methods but you can also use it on privale field adding @XmlAccessorType(XmlAccessType.FIELD) on class – David Geirola Jul 13 '17 at 14:06
  • I wanted to suggest to just put these into the answer itself, so every reader can easily look these things up. I took the liberty to edit your question accordingly, I hope that's fine with you :-) – domsson Jul 13 '17 at 14:08
  • ok sorry i didn't understand I'm in a hurry :) I'll keep that in mind ;) – David Geirola Jul 13 '17 at 14:13