Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create object without declaring class?

Tags:

groovy

Is it possible to create object without declaring class? Like in JavaScript obj = {a: '1'}; console.log(obj.a)

like image 446
fedor.belov Avatar asked Feb 16 '12 14:02

fedor.belov


People also ask

Can an object be created without class?

We can create an object without creating a class in PHP, typecasting a type into an object using the object data type. We can typecast an array into a stdClass object. The object keyword is wrapped around with parenthesis right before the array typecasts the array into the object.

Can we create an object without class in Java?

No, there is no such a feature, you have to type out the full type name(class name).

Can you create an object in its own class?

We can use it to create the Object of a Class. Class. forName actually loads the Class in Java but doesn't create any Object. To create an Object of the Class you have to use the new Instance Method of the Class.

Can we create object without new?

You can create an object without new through: Reflection/newInstance, clone() and (de)serialization.


1 Answers

In Groovy you must always provide the class of an object being created, so there is no equivalent in Groovy to JavaScript's object-literal syntax.

However, Groovy does have a literal syntax for a Map, which is conceptually very similar to a JavaScript object, i.e. both are a collection of properties or name-value pairs.

The equivalent Groovy code to the JavaScript above is:

def obj = [a: '1'] println obj.a 

Even though there is no class name used here you're still creating an object of a particular class (java.util.LinkedHashMap). The code above is just shorthand for:

def obj = new LinkedHashMap(); obj.a = '1' println obj.a 

The Expando class is perhaps even more similar to a JavaScript object, and is useful when you want to avoid the "overhead" of defining a class, or want a dynamic object to which any arbitrary property can be added at runtime.

like image 104
Dónal Avatar answered Sep 18 '22 20:09

Dónal