2011-01-05 33 views
2

如果一個列表綁定,我可以控制的對象是如何被實例化(對於instace調用與幾個PARAMS構造)以這種方式使用自定義ElementFactory在AutoPopulatingList:調用自定義構造函數結合地圖時

public class Foo{ 

    private List<NestedFoo> nested = new AutoPopulatingList<NestedFoo>(new ElementFactory<NestedFoo>() { 
     @Override 
     public NestedFoo createElement(int index) throws ElementInstantiationException { 
      return new NestedFoo(index); 
     }  
    }); 
} 

當集合是一個Map而不是List時,有什麼辦法可以做類似的事嗎?我的意思是,當表單發送像嵌套['fooParam']時,我想調用一個構造函數與fooParam時,地圖是'自動增長'。

感謝。

回答

4

不知道春天的任何解決方案,但GuavaMapMaker類可以創建一個計算映射:

ConcurrentMap<Key, Graph> graphs = new MapMaker() 
    .concurrencyLevel(4) 
    .softKeys() 
    .weakValues() 
    .maximumSize(10000) 
    .expireAfterWrite(10, TimeUnit.MINUTES) 
    .makeComputingMap(
     new Function<Key, Graph>() { 
     public Graph apply(Key key) { 
      // this is where your values are created on demand 
      return createExpensiveGraph(key); 
     } 
     }); 

參考:


BTW,Apache Commons/Collections也有類似的功能:

MapUtils.lazyMap(Map, Transformer)

相關問題