Search code examples
gwtgwt-platformjava.lang.class

Best way to send java.lang.Class via dispatch?


here's the setup: I'm using GWT 2.4 with gwt-platform 0.7. I have a bunch of classes that contain key-value-pairs (at the moment int->String). They are just different classes because they get saved to different tables in database via JPA.

Now I'd like to have one(!) method to fetch this data from the server.

I first tried to send to the server the classes I'd like to fetch using ArrayList<Class<?>>. And answer with HashMap<Class<?>, HashMap<Integer, String>>. But GWT doesn't allow to serialize Class<?>. This way I could get all the database entries and display them with the right class associated (that's important) very easily.

Now I am looking for another way to get it working without having to write lot's of code.

The first new idea was to have a HashMap<String, Class<?>> somewhere inside the shared folder and just transfer the String over the wire. So the client and server would have to create a new object by finding the class via the String in the HashMap.

Is there any other good solution for this?

Thank you.


Solution

  • public Enum ClassType {
      A, B, C
    }
    
    public class AType {
      HashMap<Integer, String> myHashMap;
      ClassType getClassType() {
          return ClassType.A;
      }
    }
    
    public interface TransferableHashMap extends IsSerializable {
       ClassType getClassType();
    }
    
    public interface transferService extends RemoteService {
        HashSet<TransferableHashMap> getMaps(HashSet<ClassType> request);
    }
    
    
    //somewhere on the client
    final Set<AType> as = new Set<AType>();
    final Set<BType> bs = new Set<BType>();
    final Set<CType> cs = new Set<CType>();
    
    Set<ClassType> request = new HashSet<ClassType>();
    request.add(ClassType.A);
    request.add(ClassType.B);
    request.add(ClassType.C);
    
    transferService.getMaps(request, 
      new AsyncCallback<HashSet<TransferableHashMap>>(){
    
      @Override
      public void onSuccess(HashSet<TransferableHashMap>> result) {
          for (TransferableHashMap entry : result) {
            if(entry instanceof Atype) as.add((AType)entry);
            else if(entry instanceof Btype) bs.add((BType)entry);
            else if(entry instanceof Ctype) cs.add((CType)entry);
            else throw new SerializationException();
            }
        }
      });
    

    That's how I'd do it.