2015-04-22 29 views
0

今天我看到了下面的代码:在运行时改变到一个标记接口

public Tab addTab(Component c, String caption, Resource icon, int position) { 
    Tab addedTab = super.addTab(c, i18nCaption, icon, position); 
    // if is not securized 
    if (!(addedTab instanceof SecurizedComponent)) { 
     addedTab = SecurityWrapper.createSecurityWrapper((TabSheetTabImpl)addedTab, caption); 
    } 
    return addedTab; 
} 

SecurizedComponent是一个标记接口

/** 
* 
* This is a marker interface. All securized components will be changed at runtime to implement this interface. 
* This way, is possible to know if a component has been securized asking for component instanceof SecurizedComponent 
* 
* Allows the framework not to securize components more than once 
* 
*/ 
    public interface SecurizedComponent { 

    } 

的方法createSecurityWrapper做这样的事情:

Enhancer enhancer = new Enhancer(); 
    enhancer.setSuperclass(wrapperClass); 
    enhancer.setClassLoader(source.getClass().getClassLoader()); 
    enhancer.setInterfaces(new Class[]{SecurizedComponent.class}); 

    //more stuff... 

我知道这段代码在做什么,基本上当第一次添加标签时,它会在运行时更改为i实现SecurizedComponent接口。 但我的问题是:这是一个很好的做法吗?有更好的方法来实现它吗?

回答

0

这并不令我震惊,真的。我会将支票if (!(addedTab instanceof SecurizedComponent)) {放在SecurityWrapper中,所以你不会在代码中的任何地方进行检查,并且调用带有安全对象的SecurityWrapper将不会执行任何操作。否则,我将使用带有isSecured()方法的Securizable接口,所有实现将返回false直到SecurityWrapper发挥作用。

当然,“安全”只与您的代码一样安全,因为我支持您可以更改您的班级以实施Securized并绕过检查...