Reputation: 10372
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.
Upvotes: 18
Views: 8856
Reputation: 20531
Yes! With Java 10's var
feature:
var o = new Object(){
int count = 5;
String message = "A string.";
};
System.out.println(o.count);
var
at https://stackoverflow.com/a/63073591/873282.Upvotes: 0
Reputation: 2670
Java has a feature called local classes, which are somewhat similar. They're useful for creating a class or implementing an interface that doesn't really need to be known about outside of a particular method. The scope of the local class is limited by the code block that defines it.
public void doSomething() {
class SomeLocalClass {
public int count = 5;
public String message = "A string.";
}
SomeLocalClass local = new SomeLocalClass();
System.out.println(local.count);
System.out.println(local.message);
}
Unlike anonymous types in C#, Java local classes and their fields have explicitly defined types, but I imagine they might have some overlapping use cases.
Upvotes: 4
Reputation: 8842
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");
Upvotes: 11
Reputation: 120526
No. There is no equivalent. There is no typeless variable declaration (var
) in Java that the Java compiler could fill in with the auto-generated type name to allow a.Count
and a.Message
to be accessed.
Upvotes: 15