【问题标题】:Using GWT's NumberFormat class in the shared package在共享包中使用 GWT 的 NumberFormat 类
【发布时间】:2011-06-28 16:44:00
【问题描述】:

在我的 GWT 项目中,我的服务返回我定义的 Shield 类型的对象。由于 Shield 类型同时被客户端和服务器使用,我将类定义放在共享包中。

Shield 类使用 com.google.gwt.i18n.client.NumberFormat 类(替代java.text.DecimalFormat 等) )。

问题是 NumberFormat 无法放入共享包中,因为它使用 GWT.create() 创建了 LocaleInfo 的实例。

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

【问题讨论】:

    标签: java gwt


    【解决方案1】:

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

    然后我将 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;}
    }
    

    我在那里有额外的方法,因为我使用那个类服务器端,如果它们不在那里,编译器就会适应它。

    最后,别忘了将你的超级源代码添加到你的 *.gwt.xml 中:

    <super-source path="clientStubs"/>
    

    【讨论】:

    • 那太美了。 GWT 应该有一个解决方案。
    【解决方案2】:

    总之,没有。

    共享包应仅包含客户端和服务器都使用(AND CAN)的任何逻辑或数据类型。

    gwt 提供他们的数字格式类的原因是,在他们的words -

    在某些类中,类的功能过于昂贵而无法完全模拟,因此提供了另一个包中的类似例程。

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

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

    【讨论】:

    • 谢谢@Bhat,我认为可能是这种情况。多么不幸:-(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-24
    • 1970-01-01
    • 2010-12-16
    • 2011-02-27
    • 1970-01-01
    • 2020-11-18
    相关资源
    最近更新 更多