Skip to content

Instantly share code, notes, and snippets.

@raphw
Created May 11, 2017 07:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raphw/061e65ab55f0f846e6fbdfb52c83fed1 to your computer and use it in GitHub Desktop.
Save raphw/061e65ab55f0f846e6fbdfb52c83fed1 to your computer and use it in GitHub Desktop.
Overridding a package private package.
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.implementation.FixedValue;
import java.lang.reflect.Method;
import static net.bytebuddy.matcher.ElementMatchers.named;
public class PackageConfusion {
public static void main(String[] args) throws Exception {
Sample sample = new ByteBuddy()
.subclass(Sample.class)
.method(named("value"))
.intercept(FixedValue.value("bar"))
.make()
.load(Sample.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER) // Change to 'INJECTION' for current class loader
.getLoaded()
.newInstance();
System.out.println(sample.value());
Method method = sample.getClass().getDeclaredMethod("value"); // Invoke 'value' that is owned by other class loader
method.setAccessible(true);
System.out.println(method.invoke(sample));
}
public static class Sample {
String value() {
return "foo";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment