How to create an object dynamically

I want to create an object on the fly, that is not assigned to a variable, and doesn't need a class definition.

In C#, it's possible via object initializers, or via ExpandoObject and dynamic keyword:

var ananymousObject = new { Property = "Value" }; // object initializer

or

dynamic instance = new ExpandoObject();
instance.Property = "Value";

How to do that in Android Studio?

Upvotes: 0

Views: 1751

Answers (3)

Abhishek Singh
Abhishek Singh

Reputation: 9178

Java is much more strict in this case. So the short answer is no, Java doesn't have an Expando. The syntax just doesn't support that.

However there is an Expando in Groovy which is a dynamic language on top of java.

BTW, If you're using Expando for tests, there are a lot of various Mock related solutions: EasyMock, Mockito, JMock to name a few.

Upvotes: 0

rishabh pandey
rishabh pandey

Reputation: 1

In Java you can write this "new ABC()" this creates anonymous object which doesn't have any reference here AB is any class name like new String();

Upvotes: 0

GRiMe2D
GRiMe2D

Reputation: 664

Use HashMap

HashMap<String, Object> anon = new HashMap<>();
anon.set("property", value);

Upvotes: 2

Related Questions