在我的GWT项目中,我的服务返回一个我定义的Shield类型的对象.由于客户端和服务器都在使用Shield类型,因此我将类定义放在共享包中.
该盾类使用com.google.gwt.i18n.client.NumberFormat类(补发,除其他外,java.text.DecimalFormat中).
问题是NumberFormat不能放在共享包中,因为它使用GWT.create()创建LocaleInfo的实例.
有什么办法可以在共享包中使用com.google.gwt.i18n.client.NumberFormat吗?
我通过创建一个SharedNumberFormat,然后是一个从未使用过的服务器版本的空客户端存根来解决这个问题.
这是我的SharedNumberFormat.java,您猜对了,它可以在共享代码中使用,并且可以在客户端和服务器端正常工作:
import java.text.DecimalFormat;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.NumberFormat;
/**
* The purpose of this class is to allow number formatting on both the client and server side.
*/
public class SharedNumberFormat
{
private String pattern;
public SharedNumberFormat(String pattern)
{
this.pattern = pattern;
}
public String format(Number number)
{
if(GWT.isClient())
{
return NumberFormat.getFormat(pattern).format(number);
} else {
return new DecimalFormat(pattern).format(number.doubleValue());
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后我在我的超级源代码中删除了java.text.DecimalFormat实现:
package java.text;
/**
* The purpose of this class is to allow Decimal format to exist in Shared code, even though it is never called.
*/
@SuppressWarnings("UnusedParameters")
public class DecimalFormat
{
public DecimalFormat(String pattern) {}
public static DecimalFormat getInstance() {return null;}
public static DecimalFormat getIntegerInstance() {return null;}
public String format(double num) {return null;}
public Number parse(String num) {return null;}
}
Run Code Online (Sandbox Code Playgroud)
我有额外的方法,因为我使用该类服务器端,如果它们不在那里,编译器会对它有所了解.
最后,不要忘记将超级源标记添加到*.gwt.xml:
<super-source path="clientStubs"/>
Run Code Online (Sandbox Code Playgroud)