How to understand Groovy classes as first-class citizens

I am a seasoned Java developer, but a beginner Groovy programmer that I am learning at the moment (which is great so far). As a reference, I am reading this document:

http://groovy.codehaus.org/Groovy+style+and+language+feature+guidelines+for+Java+developers

It's okay, except I don't quite understand. The documentation states that classes are first-class citizens and the suffix is .class

not needed in Groovy. But if this is the case, then how can I refer to an object type (i.e. Class) in Groovy?

Consider the following example:

def o = new Object()
println("$o, ${o.class}")

      

Which gives me the following output:

java.lang.Object@da479dd, class java.lang.Object

      

This conclusion is expected and makes sense. But what is the Groovy documentation than refer to when they say no suffix .class

is needed?

+2


source to share


2 answers


In Groovy and many other dynamic languages, everything is an object, including the class itself.

Say you have a Circle class in java. You must call Circle.getClass () on the class object you are dealing with. In many dynamic languages, the class itself does not need to be specified. Let's say you have a class

class Miu {}

      

and each subsequent reference to Miu will refer to the class object itself



Miu.class
Miu

      

both will evaluate to the same object

In other words, Java and earlier in C ++ did not have eval (), so the class definition itself cannot be directly included in the class object. The OO model is more like class-oriented programming rather than true object-oriented, since classes are not objects. In later interpreted dynamic languages, classes are themselves objects.

+3


source


You are mixing two different things. You don't need .class when you refer to a specific class, so if you have a Foo class and want to refer to it, you don't need to type Foo.class

, you just type Foo

. (This is what the article you link to describes.) But when you have an object of some kind and want to know its class, you would still use .class

(where .class is actually short for the getClass method call) ... Note that if you have a card and want to know its class, you must enter getClass()

so it doesn't think you don't mean the key of the card called class.



+3


source







All Articles