How to make a Groovy method truly protected
groovy
Solution
Short answer: Groovy does not enforce visibility checks.
Longer answer Protected has a meaning in Java, that you surely know. I mention it only for the interested reader: http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6.2
It is not that Groovy does not set the same modifier. So seen from Java the member will be protected just as in Java itself. It is more that Groovy does not perform the visibility check at runtime (or compile time) and might even use reflection to force accessibility. Groovy has to do so, because in general in Groovy the class accessing the member is one of the runtime. That means Groovy would have to emulate visibility checks at runtime, but for this some kind of "origin of call" is required, but not always available in Groovy due to the meta object protocol lacking the ability to properly transfer it.
Using @CompileStatic things are different. Here a direct access to the member is produced. Only it should have failed compilation already and not fail at runtime with IllegalAccessError.
Problem
Trying to make a method in groovy `protected`: ``` package com.foo class Foo { protected def getSomething(){ } } ``` This doesn't work since groovy by default makes pretty much everything visible, so I tried using `@PackageScope` ``` package com.foo import groovy.transform.PackageScope @PacakgeScope class Foo { def getSomething(){ } } ``` This sort of works, but only if the caller uses `@CompileStatic`... ``` package com.bar class Bar { @CompileStatic static void main(args){ def f = new Foo() println f.getSomething() } ``` The above throws `IllegalAccessError`, that's nice, but without `@CompileStatic`, no error is generated; not so nice. I can't force users to compile statically, so is there any alternative to enforce `protected` methods? From Groovy Documentation Protected in Groovy has the same meaning as protected in Java, i.e. you can have friends in the same package and derived classes can also see protected members. Ok, if `protected` has the same meaning in Groovy but isn't enforced as such, doesn't that erode its meaning? Maybe I'm missing something,