In C#, you can do the following:
var objResult = new { success = result };
Is there a java equivalent for this?
Anonymous object in Java means creating an object without any reference variable. Generally, when creating an object in Java, you need to assign a name to the object. But the anonymous object in Java allows you to create an object without any name assigned to that object.
An object which has no reference variable is called anonymous object in Java. Anonymous means nameless. If you want to create only one object in a class then the anonymous object is a good approach.
You create anonymous types by using the new operator together with an object initializer. For more information about object initializers, see Object and Collection Initializers. The following example shows an anonymous type that is initialized with two properties named Amount and Message .
Java does not have type inference provided to C# by the var
keyword, so whilst you can create anonymous types they're not much good since you can't get at their attributes.
So you can create an instance of an anonymous class like so:
Object myobj = new Object() { public final boolean success = true; }
But since myobj
is an instance of Object
you can't access success
in your code, and as you have created an instance of an anonymous class there is by definition no way to explicitly refer to this class.
In C# var
solves this by inferring the type but there is no way to do this in Java.
Normally anonymous classes are used to create implementations of interfaces and abstract classes and so are referenced using the interface or parent class as the type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With