Search code examples
javagwtgxt

Self reference in GXT Propery access


I am reading this documentation about GXT PropertyAccess.

I am creating a Grid<Stock> which contains a custom column. This column needs a ValueProvider which provides the whole Stock :

public class MyCustomCol<T> extends ColumnConfig<T, Stock> {

  public MyCustomColl(ValueProvider<? super T, Stock> valueProvider, String header) {
    ...
  }
}

How can I express it in a GXT ProperyAccess ?

public interface StockPropertyAccess extends PropertyAccess<Stock>{

  @Editor.Path("") //Which Path should I use here? I unsuccessfully tried "" 
  ValueProvider<Stock, Stock> zis();

  ValueProvider<Stock, Integer> id();
  ValueProvider<Stock, String> name();
  ...
}

Solution

  • Instead of trying to make a generated ValueProvider type for this, there is one that already exists. But first: what is a ValueProvider that you need one that talks about the whole object?

    The idea is that it provides a sort of simple 'reflection' on properties of an object, but without actual reflection (since GWT doesn't support it). These are read/write by default, allowing both a setValue and a getValue method to not only read the value out, but optionally write something back again.

    This ValueProvider interface can easily be implemented by hand as well - there is no need to start with the PropertyAccess to do it for you if it doesnt know how to solve your problem. In the case of talking about an object itself, you can just return the original object. Here is a (partially implemented) idea of how that should look:

    public class IdentityValueProvider<T> implements ValueProvider<T, T> {
        public T getObject(T object) {
            return object;
        }
        public void setValue(T object, T value) {
            //can't do anything to set object to a new value, ignore, or throw exception
        }
        //...
    }
    

    This class actually exists in GXT, and is called IdentityValueProvider, since it returns the same object as it is given (it is an "identity function"). You can make your own if you want to customize, otherwise, just pass it in as-is:

    ColumnConfig<Stock, Stock> column = 
            new ColumnConfig<Stock, Stock>(new IdentityValueProvider<Stock>());
    

    In one of your comments, you further clarify that you need to print out id + "-" + name from the full object, so ideally you want to just return that string? This might look like this:

    public class IdAndNameStringProvider implements ValueProvider<Stock, String> {
        public String getValue(Stock object) {
            return object.getId() + "-" + object.getName();
        }
        //...
    }