classStudy { publicstaticvoid main(String[] args) { def person = new Personal(name:"Silence", age:26) println(person.printName()) println(person.printAge()) println(person.sex) } }
classPersonal { public String name publicint age
public String printName() { return"My name is $name" }
public String printAge() { return"My ag is $age" }
}
输出结果如下:
1 2 3 4 5 6 7
My name is Silence My ag is 26 Exception in thread "main" groovy.lang.MissingPropertyException: No such property: sex for class: Personal at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:65) at org.codehaus.groovy.runtime.callsite.GetEffectivePogoPropertySite.getProperty(GetEffectivePogoPropertySite.java:87) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGetProperty(AbstractCallSite.java:329) at Study.main(Study.groovy:9)
Personal.metaClass.sex = "男" def person = new Personal(name:"Silence", age:26) println(person.printName()) println(person.printAge()) println(person.sex)
可以看出我们注入了一个sex的字段,输入结果如下:
1 2 3
My name is Silence My age is 26 男
当然了,注入静态变量也是类似,加上static即可。
注入新方法
看到我们输入性别的时候,发现好像和上面对比,不工整,那就自己整一个工整的,修改代码:
1 2 3 4 5 6 7 8
Personal.metaClass.sex = "男" Personal.metaClass.printSex = { -> "My sex is $sex" } def person = new Personal(name:"Silence", age:26) println(person.printName()) println(person.printAge()) println(person.printSex())