问题描述
谁能解释@TypeChecked 和@CompileStatic 的区别?
Can someone explain the difference between @TypeChecked and @CompileStatic?
我读到使用@TypeChecked 无法在运行时添加新方法.不允许使用哪些其他功能?
I read that with @TypeChecked it is not possible to add new methods at runtime. What other features are not allowed?
@CompileStatic 允许哪些 Groovy 特性?与 groovyc 和 @CompileStatic 相比,字节码是否与使用 javac 编译的相同?
Which Groovy Features are allowed with @CompileStatic? Is the bytecode same as compiled with javac in compare to groovyc and @CompileStatic?
推荐答案
主要区别在于 MOP(元对象协议):@TypeChecked
保持方法通过 MOP,而 @CompileStatic
生成类似于Java 字节码的方法调用.这意味着它们的语义不同,但也意味着您仍然可以在 @TypeChecked
代码之上应用元编程,只要可以在编译时解析方法调用即可.
The major difference is the MOP (Meta Object Protocol): @TypeChecked
keep methods going through the MOP, while @CompileStatic
generate method calls similar to Java's bytecode. This means their semantic are different, but it also means you can still apply metaprogramming on top of a @TypeChecked
code, as long as the method call can be resolved at compile time.
以下代码显示了 MOP 作用于 @TypeChecked
代码,而不是作用于 @CompileStatic
代码:
The following code shows the MOP acting on a @TypeChecked
code, and not on @CompileStatic
code:
import groovy.transform.CompileStatic as CS
import groovy.transform.TypeChecked as TC
class Foo {
def bar = "bar"
}
class TestTC {
Foo foo
TestTC() {
foo = new Foo()
foo.metaClass.getBar = { "metaClass'd bar" }
}
@TC
def typed() {
foo.bar
}
@CS
def compiled() {
foo.bar
}
}
assert new TestTC().typed() == "metaClass'd bar"
assert new TestTC().compiled() == "bar"
对于 @CompileStatic
,是的,Groovy 尝试生成接近 javac
输出的字节码,因此,他们的表现非常接近,只有少数例外.
For @CompileStatic
, yes, Groovy tries to generate bytecode close to what javac
would output, thus, their performance are very close, with a few exceptions.
(更新于 2016-01-13)
@CompileStatic
和 @TypeChecked
都允许:
- Closures (including Closure delegations through
@DelegatesTo
); - ASTs (which can be used for compile-time metaprogramming);
- Groovy's syntatic sugar, like those on regex, lists, maps, operator overload and the likes;
- Extensions.
对于 @TypeChecked
,您还可以通过 类型检查扩展,提供更大的灵活性.@CompileStatic
也支持这一点,但它是一个 限制更多.
For @TypeChecked
, you can also instruct the compiler to ignore some type checks through a Type Checking Extensions, allowing more flexibility. @CompileStatic
also support this, but is a little more restrictive.
这篇关于@TypeChecked 和 @CompileStatic 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!