2015-04-22 38 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並繞過檢查...