Is there any way to override library classes in a Java application

12.2k Views Asked by At

I am using Eclipse and Netbeans, now preferring Netbeans. If developing a system class that is in the java library (such as FileReader) is there any way to add that class into an application and have the local one supercede the library copy?

The idea is to be able to work on augmenting a specific class at a time while still using the normal jdk.

Specifically I am working with java.lang.StringBuilder and java.io.FileWriter.

I wrote a modified StringBuilder class. If I create it in my directory: java/lang/FastStringBuilder

javac complains that I am trying to compile a restricted package java.lang.

If I rename the package, then it cannot inherit from AbstractStringBuilder which is not public.

They are making this way harder than it needs to be.

2

There are 2 best solutions below

5
On

It is really-really bad idea in Java.

Do you need your own FileReader? - make it in your package and use it.

Do you need to use methods from standard FileReader? - extend or wrap it in your own FileReader and use it.

But never-ever try to replace any classes from any libraries regardless from where they are -in JDK or other third party frameworks.

For very rare and worse cases you can use AOP, but it is really painful and also another "better bad idea".

2
On

Instead of

import java.io.FileReader;

you just need

import package.of.your.FileReader;

to use your implementation instead of the standard one.