Created
September 26, 2018 10:18
-
-
Save artem-smotrakov/bf05dbb8cdf012db5c979f18e7f8453e to your computer and use it in GitHub Desktop.
Accessing private fields with synthetic methods in Java, see also https://blog.gypsyengineer.com/en/security/accessing-private-fields-with-synthetic-methods-in-java.html
This file contains 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
package com.gypsyengineer.innerclass.field; | |
public class AccessPrivateField { | |
public static void test02(ClassLoader cl) throws Exception { | |
System.out.println("Test #2: try to modify a private field with different classloader"); | |
System.out.println(" (an exception is expected)"); | |
// Load AccessPrivateField class with different classloader | |
Class clazz = cl.loadClass( | |
"com.gypsyengineer.innerclass.field.AccessPrivateField"); | |
// Make sure that we loaded a new class | |
if (AccessPrivateField.class.equals(clazz)) { | |
throw new RuntimeException("Couldn't load different AccessPrivateField with new class loader"); | |
} | |
// Get "go" method from clazz, and run with an instance of Outer | |
// Note that Outer class and clazz were loaded by different classloaders | |
Outer outer = new Outer(); | |
Method m = clazz.getDeclaredMethod("go", Object.class); | |
m.invoke(null, outer); | |
} | |
// Modify a private field by calling a synthetic method | |
public static void go(Object t) throws Exception { | |
Method m = t.getClass().getDeclaredMethod( | |
"access$002", t.getClass(), int.class); | |
m.invoke(null, t, -1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment