在共享包中使用GWT的NumberFormat类

luk*_*sen 5 java gwt

在我的GWT项目中,我的服务返回一个我定义的Shield类型的对象.由于客户端和服务器都在使用Shield类型,因此我将类定义放在共享包中.

类使用com.google.gwt.i18n.client.NumberFormat类(补发,除其他外,java.text.DecimalFormat中).

问题是NumberFormat不能放在共享包中,因为它使用GWT.create()创建LocaleInfo的实例.

有什么办法可以在共享包中使用com.google.gwt.i18n.client.NumberFormat吗?

Rya*_*ton 5

我通过创建一个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)


Jai*_*Jai 2

简而言之,不。

共享包应该只包含客户端和服务器(并且可以)使用的任何逻辑或数据类型。

gwt 提供数字格式类的原因是,用他们的话说-

在某些类中,该类的功能成本太高而无法完全模拟,因此在另一个包中提供了类似的例程。

反之亦然,GWT 的实现NumberFormat是特定于 javascript 的,当然不能在服务器端使用(在您的情况下是 Java)。

您必须尝试将格式化逻辑分别移出此类并移至服务器端(使用 java 的 NumberFormat)和客户端(使用 gwt 的 NumberFormat)。您可以将其余部分保留在共享包中。