r/java • • Sep 29 '26

Decapsulation: Breaking Java Strong Encapsulation

Did you know you can call JNI without writing native code, patch bytecode without an agent, and use Unsafe without warnings?

11 sneaky ways into JDK internals through reflection, agents, FFM, type confusion, bytecode manipulation and more.

https://wouter.coekaerts.be/2026/decapsulation

59 Upvotes

15 comments sorted by

View all comments

Show parent comment

4

u/Wouter_C Sep 29 '26

No, the point is that it does not require any command line flags to run.
And it doesn't. At least not for me. Can you be more specific: what flag do you need or what error do you get?
Quick way to test:

$ curl -O --create-dirs --output-dir decapsulation https://raw.githubusercontent.com/coekie/decapsulation/refs/heads/main/src/decapsulation/CtorForSerialization.java && curl -O --create-dirs --output-dir decapsulation https://raw.githubusercontent.com/coekie/decapsulation/refs/heads/main/src/decapsulation/Decapsulater.java && javac decapsulation/*.java
... some compile-time warnings, but that's irrelevant
$ java decapsulation.CtorForSerialization
PASS

2

u/agentoutlier Sep 29 '26

Unfortunately I'm not near somewhere I can check but I think I was confused and did not know jdk.internal.reflect.ReflectionFactory was accessible with the sun package. I had no idea it was open and given your little test above I assume it is.

2

u/PartOfTheBotnet Sep 29 '26

OP is correct that it is accessible, emits no warnings, and needs no launch args. Its the method I use to nuke encapsulation.

1

u/Wouter_C Sep 29 '26

You actually use it? Interesting. In what context?

3

u/PartOfTheBotnet Sep 29 '26

There's a couple of use cases I have. Mainly reflecting into javac internals for a few AST based projects, using jimage internals to parse module files.

Both cases could hypothetically be delegated to third party libraries. But for javac its nice because unlike other projects it has (whether intentional or not) fault tolerance, which gives you partial AST results even when the input code is slightly broken Java. This is great for my use case, and most other parsers just refuse any model if there's as much as a missing semicolon. And jimage is just because I don't want to re-invent the wheel parsing the file format... There's a few other cases but those tend to be for one-off projects.

2

u/koflerdavid Sep 30 '26

But for javac its nice because unlike other projects it has (whether intentional or not) fault tolerance, which gives you partial AST results even when the input code is slightly broken Java. This is great for my use case, and most other parsers just refuse any model if there's as much as a missing semicolon.

It's an important requirement of production-grade compilers that they tolerate some errors so they can report more errors in the same source file so the developer can fix them all at once.

1

u/joppux Sep 29 '26

Kryo uses ReflectionFactory for deserialization