Just launch the JVM with an appropriate security manager which prevents reflection. You should run code you don't trust under a pretty stringent security manager.
You don't need to change the String
class - just run in a tighter environment. If you're unable to control the environment like this, chances are you couldn't enforce your own "custom" String
class anyway.
As an example:
c:\Users\Jon\Test>java -Djava.security.manager StringAPI
Exception in thread "main" java.security.AccessControlException: access denied
("java.lang.RuntimePermission" "accessDeclaredMembers")
at java.security.AccessControlContext.checkPermission(Unknown Source)
at java.security.AccessController.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkMemberAccess(Unknown Source)
at java.lang.Class.checkMemberAccess(Unknown Source)
at java.lang.Class.getDeclaredField(Unknown Source)
at StringAPI.main(StringAPI.java:5)
That's just using the default policy (when the security manager is enabled) but you can also specify a custom policy.