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.
This doesn't directly answer your question, but have you tried this?
http://gwtreflection.sourceforge.net/
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With