سؤال

I am looking for an elegant solution to writing methods on DTO's

The problem arises from the fact that methods on a DTO can be used both on the client side and server side. Subsequently problems arise when you make use of any Client or server side specific methods. This generally results in an java.lang.NoClassDefFoundError exception.

The project that I am currently working on uses GWT and spring. I experienced this problem when trying to format an date on a DTO. The format method was throwing an java.lang.NoClassDefFoundError when GWT.create(GlobalConstants.class) was called. I am looking for an elegant way to differentiate if an method is being called from the server side or client side and adapt the implementation of the method accordingly.

هل كانت مفيدة؟

المحلول

First off, if you have such methods, then your object is not just a DTO (by definition, a DTO only has accessors and mutators).

That being said, there are several ways to solve your problem with your objects.

  • to solve the NoClassDefFoundError, use com.google.gwt.core.shared.GWT instead of com.google.gwt.core.client.GWT. The shared class is present in both gwt-user.jar and gwt-servlet.jar.
  • You can use GWT.isClient() to tell whether you're on the client-side or server-side and branch to the appropriate code.
  • Starting with GWT 2.6, GWT.create() can be used outside of a GWT client-side context, so you can make it work on the server-side (you have to provide your own ClassInstantiator to com.google.gwt.core.server.ServerGwtBridge.getInstance()#register())
  • If you have a server-side-specific method that wouldn't even transpile to JavaScript, starting with GWT 2.6, you can annotate it with @GwtIncompatible (any such annotation will work, the package doesn't matter, only the annotation name) and GWT will do as if it isn't there at all.
  • finally, when none of the above works, you can "fork" your code into a super-source, so as to provide distinct server-specific and client-specific implementations. See “Overriding one package implementation with another” in the GWT documentation.
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top