在异常处理的接口中初始化静态字段

时间:2011-08-10 17:49:21

标签: java interface exception-handling static field

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

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

这当然会导致编译错误,导致此方法调用引发的异常处理不当。但我不能将静态块放入接口。我想过建立一个Enum,但也许有人已经遇到过这个问题。事实上,将这个静态字段放入类中是不可能的,因为我必须使用接口。

提前致谢。

2 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分: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 }
              }
         }

    }