Ashwin Parcha
Ashwin Parcha

Reputation: 51

How to edit native Java classes

For example, I would to add some new methods to the BufferedReader class. Would that be possible? If so, how would I go about accomplishing that?
Any suggestions?

Upvotes: 1

Views: 194

Answers (4)

Cristian Meneses
Cristian Meneses

Reputation: 4041

I would not recommend you tu modify native classes, since they are widely used by code running in the JVM, and any mistake could cause severe problems.

You shoud extend those classes and override existing methods, or create new ones, to achieve the behavior you want.

Upvotes: 0

Jimmy Miller
Jimmy Miller

Reputation: 33

If you want to add a new method to BufferedReader such that it will be available to everyone using a BufferedReader object, then there's no easy way of doing this in Java. However, you can create a new class that extends BufferedReader:

class MyNewTypeOfReader extends BufferedReader {
    public void myNewMethod() {
        //Code here...
    }
}

Now, every time you create a MyNewTypeOfReader object, you'll have all of the methods available to BufferedReader, plus your new method.

Upvotes: 1

Thihara
Thihara

Reputation: 6969

You can, but you will have to keep a separate build of the JDK for that if your changes are rejected by something like Open JDK.

A much better option will be to use delegation and create your own class with the necessary functionality.

Upvotes: 0

Keith
Keith

Reputation: 4184

You can extend BufferedReader (for example). That is probably the most portable, and most recommended way to "edit" JDK classes.

Upvotes: 1

Related Questions