我有如下场景,其中有一个 World
只有一个私有(private)构造函数和另一个类的类 App
.
如代码所示,World
的新实例可以在App
里面创建尽管在 World
中只有私有(private)构造函数.
它在 Java 中是被禁止的,我认为它在 groovy 中也是被禁止的,但是 App
运行没有任何错误。
// World.groovy
class World {
private World() {
}
}
// App.groovy
class App {
static void main(String[] args) {
def world = new World()
println world
}
我不明白这在 groovy 中是如何实现的。 另一个类如何在 groovy 中实例化一个只有私有(private)构造函数的类?
最佳答案
Groovy 不识别私有(private)访问修饰符。 See this question. Groovy 中没有任何私有(private)内容。
至于 Groovy 是如何做到的,Groovy 正在为您在 Groovy 中编写的内容生成类。它可以在类文件中编写它想要的任何访问修饰符。但是您也可以使用 Groovy 来检查 Java 代码的私有(private)部分。 Groovy 在构造函数上调用 setAccessible
作为 AlexR's answer demonstrates .
安全管理器可以防止这种事情发生。在 groovysh 中,安全管理器是 org.codehaus.groovy.tools.shell.util.NoExitSecurityManager
,它仅在其父级为非空时才检查权限。在 groovysh 中,它的父级为空。
Groovy 依赖于设置“suppressAccessChecks”权限才能运行。 groovy.policy file for the core-groovy project有这个通知:
/* Notes on the contents of this policy file:
*
* The following methods in groovy have privileged operations wrapping
* setAccessible. If these wrappers are not provided, most codebases below
* must have the following grant:
* permission java.lang.reflect.ReflectPermission "suppressAccessChecks";
* MetaMethod.createMetaMethod
* MetaMethod.invoke(Object Object[])
* ReflectionMetaMethod.invoke(Object Object[])
* DefaultGoovyMethods.dump(Object)
*/
有一个page on Groovy's website of "things you can do but better leave undone" ,它在这里列出了隐私问题:
- Disregarding other objects' privacy
When accessing methods, fields, or properties of other classes, make sure that you do not interfere with private or protected members. Currently Groovy doesn't distinguish properly between public, private, and protected members, so watch out yourself.
正如 Tim Yates 在链接问题中所说的那样,尚不清楚这是缺陷还是功能。鉴于它可能会破坏现有代码,我认为它不太可能很快得到“修复”,如果有的话。
关于java - 在 groovy 中仅使用另一个类的私有(private)构造函数实例化一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23248943/