Skip to content

Instantly share code, notes, and snippets.

@artem-smotrakov
Created September 26, 2018 10:18
Show Gist options
  • Save artem-smotrakov/bf05dbb8cdf012db5c979f18e7f8453e to your computer and use it in GitHub Desktop.
Save artem-smotrakov/bf05dbb8cdf012db5c979f18e7f8453e to your computer and use it in GitHub Desktop.
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