David Sykes
David Sykes

Reputation: 7269

How can I dynamically access property of Java object in GWT?

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.

Upvotes: 6

Views: 5015

Answers (3)

Lucas A.
Lucas A.

Reputation: 406

You can use GWT's AutoBean Framework. Here's a 2-minute-quick-and-dirty example:

public interface Person {    
    public String getName();    
    public void setName(String name);    
}


public String getPropertyValue(Person p, String propertyName){
    return AutoBeanUtils.getAllProperties(AutoBeanUtils.getAutoBean(p)).get(propertyName);
}

Upvotes: 0

Joao Pereira
Joao Pereira

Reputation: 2534

Check this solution:

http://jpereira.eu/2011/01/30/wheres-my-java-reflection/

Hope it helps.

Upvotes: 0

blwy10
blwy10

Reputation: 4892

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

http://gwtreflection.sourceforge.net/

Hope this helps!

Upvotes: 2

Related Questions