javaanonymous-types

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


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."};

Or does this concept go against the Java paradigm?

EDIT:

I suppose using Hashable() in Java is somewhat similar.


Solution

  • 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<String,Object> a = new HashMap<String,Object>();
    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");