Is it possible to create object without declaring class? Like in JavaScript obj = {a: '1'}; console.log(obj.a)
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.
No, there is no such a feature, you have to type out the full type name(class name).
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.
You can create an object without new through: Reflection/newInstance, clone() and (de)serialization.
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.
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