Difference between @TypeChecked and @CompileStatic

后端 未结 2 1063
甜味超标
甜味超标 2020-12-14 15:19

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 oth

相关标签:
2条回答
  • 2020-12-14 15:43

    tl/dr;

    • @TypeChecked just checks types during compiling, but compiled code behaves same as without @TypeChecked
    • @CompileStatic checks similar to @TypeChecked, but also modifies the code to be type-safe at runtime, meaning methods using dynamic programming will break.
    0 讨论(0)
  • 2020-12-14 15:54

    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.

    0 讨论(0)
提交回复
热议问题