简体   繁体   中英

Bypass visibility modifiers in Java

I need to access private and protected methods of 3rd party lib. I cannot use reflections due to performance requirements. Maybe there are any compiler settings allowing me to do this?

One way could be to modify the modifier of your methods then re-generate the bytecode using a library that allows to manipulate the bytecode such as Javassist then patch your 3rd party library to replace the old classes with the new generated classes.

So for example, in the class org.apache.commons.io.FileUtils there is a method of type private static long sizeOf0(File file) , let's say that I want to make it public .

With Javassist you would proceed as next to generate your new FileUtils.class :

ClassPool pool = ClassPool.getDefault();
// Get the class org.apache.commons.io.FileUtils which is the class that 
// contains the method to modify
CtClass fileUtilsClass = pool.get("org.apache.commons.io.FileUtils");
// Get the class java.io.File which is the type of the parameter
CtClass fileClass = pool.get("java.io.File");
// Get the method to which we want to change the modifier
CtMethod method = fileUtilsClass.getDeclaredMethod("sizeOf0", new CtClass[]{fileClass});
// Set the modifier of the method to public
method.setModifiers(Modifier.PUBLIC);
// Write the new FileUtils.class in the user home directory following the package name
fileUtilsClass.writeFile(".");

From here, you can simply replace the old FileUtils.class directly into the jar and rename the jar to indicate that it is not the original path but a patched jar file. So for example, here I could rename commons-io-2.5.jar into something like commons-io-2.5-patch-01.jar .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM