在接口中初始化静态字段并进行异常处理

3

实际上我想在一个界面中执行以下操作:

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

当然,这会导致编译错误,因为该方法调用引发的异常没有得到适当处理。但我无法将静态块放入接口中。我考虑过构建一个枚举,但也许已经有人遇到过这个问题。实际上,将此静态字段放入类中并不是一个好选择,因为我必须使用接口。
提前感谢。

1
为什么你必须使用接口?这听起来几乎不是一个有用的要求...这是严肃的应用程序代码。无论如何都没有东西放到接口中。 - Stefan Schubert-Peters
@pvblivs 当我“设计”我的应用程序/框架时,我决定使用接口。这是有它的原因的,但是可能会有另一种实现相同功能的方法。 - mozi
2个回答

4

你能否创建一个静态辅助类,用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的方法。=) - mozi
如何分配方法getModulus = ObjectMethodHelper.getModulusMethod(),其中公共静态void getModulusMethod()的返回类型为void。 - Abhijit Chakra
@AbhijitChakra:发现得好。已修复。 - StriplingWarrior

4
您可以通过一些间接方式来处理这个问题。(代码未经测试。)
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 }
              }
         }

    }

非常有趣!非常感谢。这看起来正是我想要做的。 - mozi
至少还有一个小错误,可能是在我的代码中或者在你的代码中。我复制你的代码时出现了编译错误,因为这个静态常量字段无法初始化。移除 final 关键字(如预期的那样)解决了这个“问题”,但会导致你可以覆盖它的微不足道的问题。 - mozi
@mozi 由于我刚刚发布了我的想法,没有编译或测试它,所以发布的代码中很可能存在编译错误。 - emory
当然了...只是写了这个注释,以免其他人可能会复制粘贴并感到困惑。 - mozi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接