tags:

views:

32

answers:

1

Using GWT I have a Java class:

public class Pojo {
  private String name;
  public String getName() { return name; }
  public void setName(String name) { this.name = name; }
}

The above class is shared between the client and server side code.

From the client code I would like to dynamically access the property. That is, I would like to write a method with the following signature:

public String getProperty(Object o, String propertyName)

Such that the following code would work:

Pojo pojo = new Pojo();
pojo.setName("Joe");
getProperty(pojo, "name");    // this should return "Joe"

Java reflection is obviously out. And I have tried the following JSNI method:

public static native String getProperty(Object o, String name) /*-{
  return o[name];
}-*/;

But that does not work.

The special syntax for accessing Java objects from JavaScript can't be used either as I want this to be dynamic.

Any ideas on how I can do this?

For completeness, I will also want to be able to set a property dynamically as well.

EDIT: blwy10's answer was a great tip to get me searching using "gwt reflection" instead of with terms like "dynamic property access". This lead me to gwt-ent, which has an very elegant reflection solution. I am going to try this one, as it does not require a separate code generation step.

+1  A: 

This doesn't directly answer your question, but have you tried this?

http://gwtreflection.sourceforge.net/

Hope this helps!

blwy10
Thanks for the tip. That got me googling using different terms, which got me this: http://code.google.com/p/gwt-ent/I like this one better, as it does not require a separate code generation step. It is integrated into the GWT compile step.
David Sykes