我应该在多大程度上防范不受信任/潜在恶意的接口实施?

时间:2014-01-07 14:27:34

标签: java security interface

我应该在多大程度上防范不可靠的接口实现?也就是说,除了你自己的代码之外,由任何人或任何东西派生的实例。

安全性和恶意实现当然是主要关注点,但我也在考虑防止错误的实现使错误来自我的代码。例如,如果他们的toString()抛出异常,那么我的异常是有用的信息

throw  new RuntimeException("Something went wrong: Debugging information: [" + interfaceImplementation + "]");

将被抑制(其类型将被抑制),而只是java.lang.NullPointerException(例如),没有任何线索来解决实际问题。

我希望防止这些问题中最明显的类型,而不是在每个接口调用时使用try-catch乱丢我的代码。

实现接口本身的“接口包装器”怎么样,但实际上什么都不做,只是将调用传递回实际实例,并尝试捕获函数所记录的所有可能异常

采用这个简单的界面:

public interface UserName  {
   void setName(String s_name);
   String getName();
}

用它包裹它:

public class IWUserName implements UserName  {
   private final UserName uni;
   public IWUserName(UserName un_instance)  {
      if(un_instance == null)  {
         throw  new NullPointerException("constructor: un_instance");
      }
      uni = un_instance;
   }
   public UserName getUserNameInstance()  {
      return  uni;
   }
   public String setName(String s_name)  {
      RuntimeException rtxUnknown = null;
      try  {
         return  getUserNameInstance().setName(s_name);
      }  catch(NullPointerException npx)  {
         if(s_name == null)  {
            throw  npx;            //Documented possibility. Just rethrow.
         }
         rtxUnknown = npx;
      }  catch(IllegalArgumentException iax)  {
         if(s_name != null  &&  s_name.length() == 0)  {
            throw  iax;            //Documented possibility. Just rethrow.
         }
         rtxUnknown = iax;
      }  catch(RuntimeException rtx)  {
         rtxUnknown = rtx;
      }
      throw  new RuntimeException("Attempting getUserNameInstance().setName(s_name), s_name=\"" + s_name + "\"", rtxUnknown);
   }
   public String getName()  {
      try  {
         return  getUserNameInstance().getName();
      }  catch(RuntimeException rtx)  {
         //There is NO situation where getName() should throw an exception
         throw  new RuntimeException("Attempting getUserNameInstance().getName()", rtx);
      }
   }
}

IW*类包含大量代码,显然必须维护以保持与接口函数的文档/规范一致,但使用的最终结果非常简洁:

public static final void main(String[] igno_red)  {
   UserName un = BasicUserName.newInstance();
   IWUserName iwun = new IWUserName(un);

   iwun.setName("Kermit");
   System.out.println(iwun.getName());
}

并且似乎可以防范我正在考虑的大多数事情。

这个IW的想法有多疯狂,如果它是疯了, 你会在多大程度上防止这类事情发生?假装保持这个IW代码是一种痛苦,使用它会产生任何其他负面影响吗?

(我不是要求对这个IW类的具体设计进行代码审查。这只是作为一个例子,说明如何处理这种保护理念,以及如何处理它。)

感谢您的任何建议。

0 个答案:

没有答案