Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Java equivalent of creating an anonymous object in C#?

Tags:

java

c#

In C#, you can do the following:

var objResult = new { success = result };

Is there a java equivalent for this?

like image 276
Cody Avatar asked Dec 13 '11 11:12

Cody


People also ask

What is anonymous object in Java?

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.

Are anonymous objects possible in Java?

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.

How do I make an anonymous object?

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 .


1 Answers

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.

like image 122
Dave Webb Avatar answered Sep 21 '22 16:09

Dave Webb