问题描述
有人可以解释@TypeChecked和@CompileStatic之间的区别吗?我用@TypeChecked阅读过,不能在运行时添加新的方法。
还有哪些其他功能是不允许的?
允许@CompileStatic使用哪些Groovy功能?
与groovyc和@CompileStatic相比,字节码与javac编译的相同吗?
主要区别在于MOP(元对象协议): @TypeChecked
保持方法通过MOP,而 @CompileStatic
生成类似于Java字节码的方法调用。这意味着它们的语义是不同的,但是这也意味着您仍然可以在 @TypeChecked
代码的顶部应用元编程,只要方法调用可以在编译时解析。
下面的代码显示了MOP作用于 @TypeChecked
代码,而不是 @CompileStatic
code:
导入groovy.transform.CompileStatic作为CS
import groovy。 transform.TypeChecked为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
将输出的字节码,因此,但有一些例外情况。 b
$ b b
$ b
$ b @CompileStatic
和 @ TypeChecked
将允许:
- 闭包(包括通过
@DelegatesTo
); - AST(可用于。
对于 @TypeChecked
,您还可以指示编译器通过来忽略某些类型的检查,从而提供更大的灵活性。 @CompileStatic
也支持这个,但是。
Can someone explain the difference between @TypeChecked and @CompileStatic?
I read that with @TypeChecked it is not possible to add new methods at runtime. What other features are not allowed?
Which Groovy Features are allowed with @CompileStatic? Is the bytecode same as compiled with javac in compare to groovyc and @CompileStatic?
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.
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"
For @CompileStatic
, yes, Groovy tries to generate bytecode close to what javac
would output, thus, their performance are very close, with a few exceptions.
(Updated 2016-01-13)
Both @CompileStatic
and @TypeChecked
will allow:
- 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.
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之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!