Information-hiding in Groovy (using closures? naming conventions?)
SecurityManager
don't run following code from
GroovyConsole
. only from groovy command line.
def sm = new SecurityManager()
System.setSecurityManager(sm)
//without previous lines the following code will run successfully
println new ByteArrayOutputStream().buf
this will throw the following exception
Caught: java.security.AccessControlException: access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.codehaus.groovy.tools.GroovyStarter.rootLoader(GroovyStarter.java:109)
at org.codehaus.groovy.tools.GroovyStarter.main(GroovyStarter.java:131)
Caused by: java.lang.ExceptionInInitializerError
at groovy.ui.GroovyMain.run(GroovyMain.java:397)
at groovy.ui.GroovyMain.process(GroovyMain.java:370)
at groovy.ui.GroovyMain.processArgs(GroovyMain.java:129)
at groovy.ui.GroovyMain.main(GroovyMain.java:109)
... 6 more
Caused by: java.security.AccessControlException: access denied ("java.util.logging.LoggingPermission" "control")
at java.security.AccessControlContext.checkPermission(AccessControlContext.java:472)
at java.security.AccessController.checkPermission(AccessController.java:884)
at java.lang.SecurityManager.checkPermission(SecurityManager.java:549)
at java.util.logging.LogManager.checkPermission(LogManager.java:1586)
at java.util.logging.Logger.checkPermission(Logger.java:422)
at java.util.logging.Logger.setUseParentHandlers(Logger.java:1799)
at org.codehaus.groovy.runtime.StackTraceUtils.<clinit>(StackTraceUtils.java:57)
... 10 more
control access with getProperty
& setProperty
class A extends GroovyObjectSupport{
private int i=555
private int j=666
def f(){
println "i=$i j=$j"
}
Object getProperty(String name){
if(name in ['i'])throw new Exception("Access to property `$name` is denied")
return super.getProperty(name)
}
}
def a=new A()
a.f()
println "a.j = ${a.j}"
println "a.i = ${a.i}"
this will allow access to member j
but not to the member i
outside of class.
output:
i=555 j=666
a.j = 666
Exception thrown
java.lang.Exception: Access to property `i` is denied
...