Java did have a Security Manager that can be used to prevent this sort of thing. The original thinking was that the Java runtime would essentially be an OS, and you could have different applets running within the runtime. This required a permission system where you could confine the permissions of parts of a Java program without confining the entire thing; which led to the Java security manager.
Having said that, the Java Security Manager, while an interesting idea, has never been good. The only place it has ever seen significant use was in webapps, where it earned Java the reputation for being insecure. Nowadays, Java webapps are ancient history due to the success of Javascript.
The security manager was depreciated in Java 17, and I believe removed entirely in Java 21.
Around 2 years ago, I got an email from a products team asking me for urgent help extending a program in time to make a sale.
I looked over the program and wrote back sonething along the lines of “this program was written almost a decade ago by an unsupervisered highschool intern. Why TF are we still using it?”.
Of course, I ended up helping them, because that highschool intern was me, and I ended up helping because no one else could figure out what highschool me was thinking.