Skip to content

Instantly share code, notes, and snippets.

@anarresian
Created June 15, 2016 09:41
Show Gist options
  • Save anarresian/fc910f4207bcec88c9c535a522ca2d65 to your computer and use it in GitHub Desktop.
Save anarresian/fc910f4207bcec88c9c535a522ca2d65 to your computer and use it in GitHub Desktop.
package tests;
import java.lang.reflect.Field;
public class VisibilityTest {
public static void main(String[] args){
try {
Class type = Class.forName("java.io.BufferedWriter");
Field defaultCharBufferSize = type.getDeclaredField("defaultCharBufferSize");
try {
defaultCharBufferSize.setInt(defaultCharBufferSize, 10);
} catch (IllegalAccessException e) {
// we can't change field value directly?
System.out.println("Direct change failed.");
System.err.println(e.getMessage());
}
defaultCharBufferSize.setAccessible(true);
defaultCharBufferSize.setInt(defaultCharBufferSize, 10);
if (defaultCharBufferSize.getInt(defaultCharBufferSize) == 10)
System.out.println("Change successful after setAccessible()");
} catch (ClassNotFoundException | NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/*
Direct change failed.
Class tests.VisibilityTest can not access a member of class java.io.BufferedWriter with modifiers "private static"
Change is successful after setAccessible().
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment