Is it possible to create object without declaring class?

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)