Guocheng
Guocheng

Reputation: 553

In Groovy what's the difference between an instance's metaClass and its class's metaClass

See the following code:

class Car implements GroovyInterceptable{}
car=new Car()
Car.metaClass.hello={println "class Car:hello"}
car.metaClass==Car.metaClass

the result is:

false

So my question is: What's the difference between car.metaClass and Car.metaClass? I did some searching, but no result. Could anyone help on this?

Upvotes: 2

Views: 77

Answers (1)

Jayan
Jayan

Reputation: 18459

car.metaClass is applicable to the object called car. You may modifiy it, but it will not be visible to other Car objects

When you modify Car.metaClass, that is will be applicable to all objects of Car.class (created after this new meta modification)

class Car implements GroovyInterceptable{}
car=new Car()

Car.metaClass.accelerate {->println "Factory tested. Safe acceleration"}
car.metaClass.accelerate  {->println "Owner modified : Random acceleration"}

def anotherCar= new Car();
anotherCar.accelerate()
car.accelerate()

Output

 Factory tested. Safe acceleration
 Owner modified : Random acceleration

Upvotes: 2

Related Questions