Activating a class using only a private constructor from another class in groovy

I have a script like the following where there is a class Worldwith only a private constructor and another class App.

As shown in the code, a new class Worldcan be created inside the class App, despite its only private constructor World.

It is forbidden in Java, and I thought it was forbidden in groovy, but it Appworks without errors.

// World.groovy
class World {
    private World() {
    }
}

// App.groovy
class App {
    static void main(String[] args) {
    def world = new World()
    println world
}

I could not understand how this is possible in groovy. How can another class instantiate a class with only a private constructor in groovy?

+4
source share
2 answers

Groovy . . . Groovy .

Groovy, Groovy , Groovy. , . Groovy Java. Groovy setAccessible AlexR.

. groovysh org.codehaus.groovy.tools.shell.util.NoExitSecurityManager, , . groovysh null.

Groovy 'suppressAccessChecks', . groovy.policy core-groovy :

/* 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)
 */

- Groovy ", , " ,

, , , . Groovy , , , .

​​ , , . , , , "" , -.

+3

. , , factory.

:

  • java.util.Pattern Pattern.compile()
  • singleton

, . Groovy, java.

Constructor c = World.class.getConstructor();
c.setAccessible(true); // This line grants you permission to access even private elements
World w = (World)c.newInstance();
+2

Source: https://habr.com/ru/post/1537739/


All Articles