views:

105

answers:

4
A: 

This isn't really a class you want, it's data. Why not use a hashmap? I really dislike "Bean" style classes--they encourage bad coding (there is no place in a generated class to put actual code, so everything ends up being manipulated by external code anyway).

You can just load a hashmap from your XML and inject it into a real object--that way you don't have to worry about actually passing a hash around, you are passing a real object with real business methods and real type safety--it just HAPPENS to use a hashmap internally to store data instead of member variables.

I've done a lot more than this, but at some point you realize Hibernate does everything you want for you.

Bill K
A: 

I think the DynaBean from Commons-BeanUtils may be what you're looking for.

A DynaBean is a Java object that supports properties whose names and data types, as well as values, may be dynamically modified. To the maximum degree feasible, other components of the BeanUtils package will recognize such beans and treat them as standard JavaBeans for the purpose of retrieving and setting property values.

Barend
A: 

Yes, you could use reflection, but what comes to my mind is working with a class that you could add property. Imagine a class that has one encapsulated HashMap using a String as a key (for the attribute name) and the value of the attribute so you could read the XML file and for evey property add the attribute to the class like. For this line:

<property name="subsystem" type="String">value123</property>


GenericClass c = new GenericClass();
c.addAttribute("subsystem", new String("value123"));
//and you could implement a get and set methods like this:
public String getAttributeValue(String attributeName)
{
   return internalHashMap.get(attributeName).toString();
}

Using this you could also implement a setAttributeValue will be quite simple I think

fredcrs
Why a hashMap? I can also do this using a LinkList?
bad question.. offcourse we need a hash
Just a note: a naive implementation of setAttributeValue() will probably allow the user of the class to set values to attributes that were not defined in the XML, therefore creating them. This might be a problem depending on the OP's needs.
IgKh
Yea I know, so you should throw an Exception when trying to set one attribute that doesnt exist, an IlegallArgumentException would be ok I think... And yeah a Hashmap so you can Map the attribute name with the value it has. You could use a LinkedList but you you have to create a class that would encapsulate the attribute name and value. So, use a Hashmap, much more simple
fredcrs
+1  A: 

If you really interested in creating a class dynamically, try Byte code Enhancement libraries like BCEL from Apache.

chedine