Groovy - 作为 vs (投射)
Groovy - as vs (cast)
以下两种转换方法之间是否存在任何实际差异:
result.count = (int) response['hits']['total']
对
result.count = response['hits']['total'] as int
我正在使用 @CompileStatic
并且编译器希望我进行转换 - 这让我想知道这两种表示法之间是否存在任何性能或实际差异。
主要区别在于转换使用继承的概念进行转换,其中 as
运算符是一个自定义转换器,可能使用也可能不使用继承的概念。
哪个更快?
这取决于转换器方法的实现。
铸造
Well, all casting really means is taking an Object of one particular
type and “turning it into” another Object type. This process is called
casting a variable.
例如:
Object object = new Car();
Car car = (Car)object;
正如我们在示例中看到的,我们正在将 class Object
的对象转换为 Car
因为我们知道该对象是 Car
deep 的实例下来。
但是我们不能做下面的事情,除非 Car
是 Bicycle
的子 class 这实际上没有任何意义(在这种情况下你会得到 ClassCastException
):
Object object = new Car();
Bicycle bicycle = (Bicycle)object;
as
运算符
In Groovy we can override the method asType() to convert an object
into another type. We can use the method asType() in our code to
invoke the conversion, but we can even make it shorter and use as.
在 groovy 中要使用 as
运算符,左手操作数必须实现此方法:
Object asType(Class clazz) {
//code here
}
如您所见,该方法接受 Class
的实例并实现自定义转换器,因此基本上您可以将 Object
转换为 Car
或将 Car
转换为 Bicycle
如果你想要这一切都取决于你的实现。
以下两种转换方法之间是否存在任何实际差异:
result.count = (int) response['hits']['total']
对
result.count = response['hits']['total'] as int
我正在使用 @CompileStatic
并且编译器希望我进行转换 - 这让我想知道这两种表示法之间是否存在任何性能或实际差异。
主要区别在于转换使用继承的概念进行转换,其中 as
运算符是一个自定义转换器,可能使用也可能不使用继承的概念。
哪个更快?
这取决于转换器方法的实现。
铸造
Well, all casting really means is taking an Object of one particular type and “turning it into” another Object type. This process is called casting a variable.
例如:
Object object = new Car();
Car car = (Car)object;
正如我们在示例中看到的,我们正在将 class Object
的对象转换为 Car
因为我们知道该对象是 Car
deep 的实例下来。
但是我们不能做下面的事情,除非 Car
是 Bicycle
的子 class 这实际上没有任何意义(在这种情况下你会得到 ClassCastException
):
Object object = new Car();
Bicycle bicycle = (Bicycle)object;
as
运算符
In Groovy we can override the method asType() to convert an object into another type. We can use the method asType() in our code to invoke the conversion, but we can even make it shorter and use as.
在 groovy 中要使用 as
运算符,左手操作数必须实现此方法:
Object asType(Class clazz) {
//code here
}
如您所见,该方法接受 Class
的实例并实现自定义转换器,因此基本上您可以将 Object
转换为 Car
或将 Car
转换为 Bicycle
如果你想要这一切都取决于你的实现。