2013-01-29 12:16 阅读 41


I need something like a property bag to throw key value pairs into. I want to create list of such objects, initialize them in bean and then use the list to render table in JSF template. I know how to do it, but I want to avoid creating some special class for that case, like OrderLineItem and using List<OrderLineItem>. I do not want to define new class.

In PHP I could use StdClass.
StdClass is a sparsely documented class in PHP which has no predefined members.

$object = new StdClass;
$object->foo = 'bar';

But, as far as I know, Primefaces <p:dataTable> list item must be an object with getter. If I want to reference <h:outputText value="#{item.title}" />, my list object should have getTitle() method.

Is there any walkaround in my case or I really need to define special class to make life easier?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

4条回答 默认 最新

  • 已采纳
    dqnhfbc3738 dqnhfbc3738 2013-01-29 12:18

    When you want a simple key/value table, then the HashMap might be what you are looking for.

    Map<String, String> myMap = new HashMap<>();
    myMap.put("foo", "bar");
    System.out.println(myMap.get("foo")); // outputs "bar"

    This example matches Strings to Strings, but you can use HashMaps to map any type to any other type. You can even create a Map<Object, Object> to create a weakly-typed map which maps anything to anything. But for most use-cases you would rather use a more specialized form.

    点赞 评论 复制链接分享
  • douhuike3199 douhuike3199 2013-01-29 12:19

    I don't know if I understood you well. But I think you mean SelectItem or JsfMap.

    点赞 评论 复制链接分享
  • dongshun1884 dongshun1884 2013-01-29 12:22

    What you need is a Map.

    You can store key-value pairs in it pretty easy:

    Map<KeyClass, ValueClass> myMap = new HashMap<KeyClass, ValueClass>();

    Use the put method to put data in it. If you use simple String values it will be like this:

    myMap.put("key", "value");
    点赞 评论 复制链接分享
  • dongping1012 dongping1012 2013-01-29 15:18

    I would recommend to use an anonymous class:

    return new HashMap<String, String>() {
        this.put("key", "value");
    点赞 评论 复制链接分享