Well, in fact I would like to do the following in an interface:
public interface ObjectMethods
{
static Method getModulus = RSAPublicKey.class.getMethod("setModulus", byte[].class, short.class, short.class);
}
This of course leads to a compile error cause the exception thrown by this method call is not handled properly. But I cannot put a static block into an interface. I thought about building an Enum, but maybe someone where already faced to this problem. In fact it would not be a opportunity to put this static field into a class beca开发者_JAVA百科use I have to use interface.
Thanks in advance.
You can handle this with a little bit of indirection. (Code is untested.)
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 }
}
}
}
Could you create a static helper class that wraps the logic with a try/catch block that swallows the exception?
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();
}
精彩评论