【问题标题】:Initializing static field in interface with exception handling使用异常处理初始化接口中的静态字段
【发布时间】:2011-08-10 17:49:21
【问题描述】:

嗯,其实我想在一个界面中做以下事情:

public interface ObjectMethods
{
    static Method getModulus = RSAPublicKey.class.getMethod("setModulus", byte[].class, short.class, short.class);
}

这当然会导致编译错误,因为这个方法调用抛出的异常没有得到正确处理。但是我不能将静态块放入接口中。我考虑过构建一个枚举,但也许有人已经面临这个问题。事实上,将这个静态字段放入一个类中并不是一个机会,因为我必须使用接口。

提前致谢。

【问题讨论】:

  • 为什么必须使用接口?这听起来几乎不像一个有用的要求......这是严肃的应用程序代码。无论如何都没有放入界面
  • @pvblivs 当我“设计”我的应用程序/框架时,我决定使用接口。这是有原因的,但可能会有另一种方法来实现我想要的相同功能。

标签: java interface exception-handling static field


【解决方案1】:

您可以通过一点间接来处理这个问题。 (代码未经测试。)

public interface ObjectMethods
    {
        public static class CONSTANTS
        {
               static final Method getModulus ;
               static
               {
                     try
                     {
                           getModulus = RSAPublicKey.class.getMethod("setModulus", byte[].class, short.class, short.class);
                     }
                     catch ( Exception cause ) { //handle it }
              }
         }

    }

【讨论】:

  • 非常有趣!!非常感谢。这看起来正是我想做的。
  • 好吧,至少我的代码或您的代码中仍然存在一些错误。复制您的代码时出现编译错误,因为无法初始化此静态最终字段。删除 final 关键字(如预期的那样)解决了这个“问题”,但会导致你可以覆盖它的 fleabite...
  • @mozi 因为我只是发布了我的想法而没有编译或测试它,所以发布的代码中很可能存在编译错误。
  • 当然...只是写评论以避免其他人可能只是 c&p 和想知道。
【解决方案2】:

您能否创建一个静态帮助类,用一个可以吞下异常的 try/catch 块来包装逻辑?

public static class ObjectMethodHelper
{
    public static Method getModulusMethod() {
        try {
            return RSAPublicKey.class.getMethod("setModulus", byte[].class, short.class, short.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

public interface ObjectMethods
{
    static Method getModulus = ObjectMethodHelper.getModulusMethod();
}

【讨论】:

  • 非常感谢您的付出,但我认为我更喜欢 emory 的方法。 =)
  • 如何分配方法 getModulus = ObjectMethodHelper.getModulusMethod(); public static void getModulusMethod() 的返回类型是 void。
  • @AbhijitChakra:很好。固定。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-22
  • 2010-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-06
  • 2021-11-29
相关资源
最近更新 更多