Groovy学习笔记

[b]1.关于object.name的行为[/b]
In Groovy, everything starts with the GroovyObject interface, which, like all the
other classes we’ve mentioned, is declared in the package groovy.lang. It looks
like this:

public interface GroovyObject {
public Object invokeMethod(String name, Object args);
public Object getProperty(String property);
public void23 setProperty(String property, Object newValue);
public MetaClass getMetaClass();
public void setMetaClass(MetaClass metaClass);
}

All classes you program in Groovy are constructed by the GroovyClassGenerator
such that they implement this interface and have a default implementation for
each of these methods—unless you choose to implement it yourself.
[b]注:主要是指程序员自己编写的类以及GDK提供的类,即除了JDK提供的类。[/b]

In Groovy code, you will often find expressions such as object.name. Here is what
happens when Groovy resolves this reference:
■ If object refers to a map, object.name refers to the value corresponding to
the name key that is stored in the map.
■ Otherwise, if name is a is a property of object, the property is referenced (with
precedence of accessor methods over fields, as you saw in section 7.4.2).
■ Every Groovy object has the opportunity to implement its own getProperty
(name) and setProperty(name, value) methods. When it does, these implementations
are used to control the property access. Maps, for example, use
this mechanism to expose keys as properties.
■ As shown in section 7.1.1, field access can be intercepted by providing the
object.get(name) method. This is a last resort as far as the Groovy runtime
is concerned: It’s used only when there is no appropriate JavaBeans property
available and when getProperty isn’t implemented.

[b]2.括号中的Map可省略[][/b]

new Account(number : 'A004', balance : 400)
println(a:1, b:2)
//等价于
new Account([number : 'A004', balance : 400])
println([a:1, b:2])


[b]3.子类构造方法会自动调用父类构造方法(与Java类似)[/b]
参见:[url]http://dean-liu.iteye.com/blog/1756787[/url]

[b]3.as关键字[/b]
参见:[url]http://johnnyjian.iteye.com/blog/160796[/url]

def l = [1, 2]
Object [] o = l as Object[]


CallSite[] arrayOfCallSite = $getCallSiteArray();
Object l = ScriptBytecodeAdapter.createList(new Object[] { Integer.valueOf(1), Integer.valueOf(2) });
return (Object[])ScriptBytecodeAdapter.asType(l, $get$array$$class$java$lang$Object());

以上两段代码是Groovy源码与其编译后反编译出来的Java源码,可以看出类型转换是使用ScriptBytecodeAdapter.asType来实现的。

3.Groovy 会自动把10.5 这样的小数倜自动装箱( Autobox ) 成java.math.BigDecimal 而非你想当然的java.lang.Float 或java.lang.Double 类型。为什么要这样?举个大多数Java 开发者都没有意识到的一个惨痛例子:写一个简短的Java 应用,它循环10 次,每次都加上0.1。你最终会得到0.99999 戒1.000001,这要看你是把和存成Double 还是Float。使用BigDecimal,你将会每次都得到1.0,和预期的一模一样。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值