在我的 GWT 项目中,我的服务返回一个我定义的 Shield 类型的对象。由于客户端和服务器都使用 Shield 类型,我已将类定义放在共享包中。
Shield 类使用 com.google.gwt.i18n.client.NumberFormat 类(替代,除其他外,java.text.DecimalFormat )。
问题是 NumberFormat 不能放在共享包中,因为它使用 GWT.create() 创建 LocaleInfo 的实例。
有什么方法可以在共享包中使用 com.google.gwt.i18n.client.NumberFormat 吗?
最佳答案
我已经通过创建一个 SharedNumberFormat 然后为从未使用过的服务器版本创建一个空的客户端 stub 解决了这个问题。
这是我的 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());
}
}
}
然后我在 super 源代码中删除 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;}
}
我在那里有额外的方法,因为我在服务器端使用那个类,如果它们不在那里,编译器会适应它。
最后,不要忘记将您的 super 源标记添加到您的 *.gwt.xml 中:
<super-source path="clientStubs"/>
关于java - 在共享包中使用 GWT 的 NumberFormat 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6510039/