Created
July 16, 2011 19:00
-
-
Save codeswimmer/1086643 to your computer and use it in GitHub Desktop.
Java: How to access a private field in a class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public static int main(String[] args) { | |
| try { Private.testFieldAccess(); } | |
| catch (Throwable e) { e.printStackTrace(); } | |
| } | |
| private static class Private { | |
| private String privateString = null; | |
| public Private(String privateString) { | |
| this.privateString = privateString; | |
| } | |
| public String getPrivateString() { | |
| return privateString; | |
| } | |
| public static final void testFieldAccess() throws Throwable { | |
| Private privateObject = new Private("The Private Value"); | |
| Field[] fields = Private.class.getDeclaredFields(); | |
| Field privateStringField = Private.class.getDeclaredField("privateString"); | |
| privateStringField.setAccessible(true); | |
| String fieldValue = (String) privateStringField.get(privateObject); | |
| System.out.println("fieldValue = " + fieldValue); | |
| String value = privateObject.getPrivateString(); | |
| System.out.println("value: " + value); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment