Search code examples
javareflectionoverridingcode-injection

How to override classes in the Java API, thus changing their behaviour using Reflection?


Is it possible to override the Exceptions class and thus inject my own methods into it, thereby changing it's overall behaviour. I believe I read somewhere that it could be done using custom class loaders or some reflection technique? I think it mentioned using a custom class loader to load your custom class rather than loading the default Java API class. If so how might one do this, for instance creating a JOptionPane exception message popup upon calling printStackTrace(e) that alerts the user to the exception message.


Solution

  • Classes in packages starting with java are protected by the JVM itself, so in order to be able to change classes in these packages, you need much more than just a different class loader. Instead of going this way, you might just set your own PrintStream using System.setErr that is opening the alert box showing text that is printed there. This then not only includes calls of printStackTrace but everything that is printed on STDERR. You might use some filtering by checking the calling stacktrace of a freshly created Exception if the call comes from a Throwable or other classes that you want to support and ignore the rest.