Is there any functionality in Java similar to anonymous C # types?

I was wondering if similar functionality exists in Java, similar to anonymous C # types:

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

Or is this concept contrary to the Java paradigm?

EDIT:

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

+8
java anonymous-types
source share
2 answers

Perhaps you mean sth like this:

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

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

Probably the OP can 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"); 
+6
source share

Not. There is no equivalent. There is no declared variable description ( var ) in Java that the Java compiler could populate with an automatically generated type name to allow access to a.Count and a.Message .

+12
source share

All Articles