Retrieve the value of an attribute of a generic object in Java

2

I'm doing a system where I read Java objects, of different types, from XML files. So I do not have a single type of object and consequently I do not know its attributes or methods. I would like to perform a search, enter a string indicating attribute and value, and that search would return all objects that had this attribute and that would equal the value in a ArrayList .

Example: I have some XML files, of type Produto , Pessoa and Carro , already read and instantiated. I want to look for objects that have the following ano: 1996 , the Produto and Carro classes have the ano attribute, however Pessoa does not have it. I would go through the objects, where they would have been analyzed if the value is equal and would take the necessary steps, if the attribute did not exist it would return null or a Exception to be treated.

Someone has an idea how I can do this recovery, the biggest problem is who can be objects of different types, is that a non-relational database job, if it were relational would be very easy, with the defined types. >

I would like something like .getAtributte (String nomeAtributo, Object o) , where the first is an attribute name and the second is the parsed object.

    
asked by anonymous 26.02.2016 / 18:01

2 answers

1

From a single entity, for example Entidade , you will need to have Map<String, Object> mapa inside it.

With each xml value obtained, you will assign in the used object mapa.put(colunaXml, valorColunaXml) .

Your getAttribute(String coluna) method should follow the pattern

for (Map.Entry<String, Object> entry : mapa.entrySet()) {
    if(entry.getKey().equals(coluna.toString()){
        return entry.getValue();
    }
}
    
26.02.2016 / 19:22
0

Create an XmlObject class that will be common to all of them.

Within XMLObject, you can put a dynamic structure as a Chained List and when you create the object, you populate the list with the objects you received from the database.

In XmlObject, you then create the method: o.getAtributte (String attribute_name)

That basically goes through the list of attributes and answer the value if it exists, or null, if the attribute does not exist in the list.

    
26.02.2016 / 18:06