How is Groovy able to access private methods of a Java class?

試著忘記壹切 提交于 2019-12-10 17:27:30

问题


Groovy can access private methods and variables of a Java class. How does Groovy do this behind the scene? Is it because of the use of invokedynamic bytecode instruction which is used by MethodHandle class? I think Java uses invokespecial instruction for calling private methods and invokevirtual for public right which respects access modifiers?


回答1:


Groovy is written in Java, so it hopefully doesn't rely on the byte code directly, it doesn't it using the Reflection API.

For more details check for java.lang.reflect in the source code, you will then see how it uses the Reflection API behind the scene.




回答2:


You can do this in Java anyway by using reflection, for example, this method will set the value of a private static field...

public static void setStaticField(Class<?> clazz, String fieldName, Object value) {
    try {
        Field field = clazz.getDeclaredField(fieldName);
        field.setAccessible(true);
        field.set(null, value);
    } catch (Exception ex) {
        throw new IllegalArgumentException("Could not set field '" + fieldName + "' of type '" + clazz.getName() + "' to: " + value, ex);
    }
}

Notice field.setAccessible(true)

This can be prevented by having an appropriate Security Manager Policy set up. See How to restrict developers to use reflection to access private methods and constructors in Java?




回答3:


you can use java.lang.reflect

import java.lang.reflect.Method

// ....

Method method = a.getClass().getDeclaredMethod('initializeSeoCode')
method.setAccessible(true)
java.lang.Object r = method.invoke(a)


来源:https://stackoverflow.com/questions/40929264/how-is-groovy-able-to-access-private-methods-of-a-java-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!