Is there a functionality in Java similar to C#'s anonymous types?

后端 未结 3 1850
星月不相逢
星月不相逢 2021-02-19 21:58

I was wondering if there exists a similar functionality in Java similar to C#\'s anonymous types:

var a = new {Count = 5, Message = \"A string.\"};

3条回答
  •  攒了一身酷
    2021-02-19 22:22

    Maybe you mean sth like this:

    Object o = new Object(){
        int count = 5;
        String message = "A string.";
    };
    

    @Commenters: of course this is a theoretical, very inconvenient example.

    Probably OP may use Map:

    Map a = new HashMap();
    a.put("Count", 5);
    a.put("Message", "A string.");
    
    int count = (Integer)a.get("Count"); //better use Integer instead of int to avoid NPE
    String message = (String)a.get("Message");
    

提交回复
热议问题