View Full Version : Best way to implement dynamic property access on a static type

19 Apr 2012, 11:02 AM
Hello Everyone,

I need to implement a declarative command pattern that can update a value on a variety of static types, given a string value for the key. These types can be modified as needed to support the pattern, but need to be operated on in a generic way (IE. I can make all these types implement a common interface). Each type must react to changes made to these properties.

Here is what I have so far:

public class Main implements EntryPoint{
public void onModuleLoad()
MyView view = new MyView();

SetPropertyCommand command = new SetPropertyCommand();
command.target = view;
command.property = "text";
command.value = "Hello World!";



GWT.log("text = " + view.getValue("text"), null);

interface IValueTarget
public void setValue(String name, Object value);

public Object getValue(String property);

class SetPropertyCommand
public String property;

public IValueTarget target;

public Object value;

public void execute()
this.target.setValue(this.property, this.value);

class MyView extends Html implements IValueTarget

private HashMap<String,Object> _properties = new HashMap<String,Object>();

public void setValue(String name, Object value)
_properties.put(name, value);

if (name == "text")
setHtml((String) value);

public Object getValue(String property)
return _properties.get(property);

This seems to work ok, but I really hate the idea idea of switching through a bunch of magic string values in every IValueTarget implementation (there are a lot of them, each with a unique set of properties that can be operated on in this manor).

Is there a way to implement this with strong typing? I was looking at using the new ValueProvider functionality to expose these properties, but then I am still not sure how I would reference them using a String value, and react to changes when a value is set.

Any guidance you can provide will be greatly appreciated.

Thanks for your time!

20 Apr 2012, 12:41 PM
Just to clarify a bit, in Actionscript I would do this by putting the logic in getters and setters. This way, all the exposed properties would be included in the API documentation. In Java I could just name my get/set methods to match whatever string value should be used to reference it, and then grab a reference to it using the reflection API. But this doesn't appear to be an option in GWT.

So I guess what my question is, is there any possible way to reference a method using a String, or do I need to implement a function in each of my types that switches through a string value and manually calls the appropriate function?

Thanks again for your time!