indira
indira

Reputation: 6687

How to override a method in a jar file?

I have a method in a class and a jar file is created using this class. The jar file is included in the project.

How can I override this method in the application?

Upvotes: 3

Views: 17266

Answers (5)

AlexR
AlexR

Reputation: 115338

@Pablo Santa Cruz is right (+1): you cannot change existing code. You have to inherit existing class and override what you want in subclass.

BUT if you really want to change something in existing compiled module you can still do it using byte-code modification techniques. There are a lot of packages that can do this. A popular higher level package that implements aspect-oriented paradigm for Java AspectJ can also help.

Upvotes: 2

Bjarni Sævarsson
Bjarni Sævarsson

Reputation: 176

If you are thinking about overriding a method in an already loaded class then look at this Java reflection: How do I override or generate methods at runtime?

Upvotes: 0

Michael Berry
Michael Berry

Reputation: 72294

If you're talking about overriding the method in terms of inheriting from the class and then overriding it (i.e. from a polymorphic viewpoint) then unless the class is final you can extend from it as you would any other.

If you're talking about changing the method behaviour inside the jar file itself, you'll need to get the source, change the method yourself, then recompile it and repackage it in another jar file. Note however I really wouldn't recommend that approach especially if the jar is a common library jar - someone maintaining your code later on will be really confused / hacked off if the behaviour of a library class has been altered (bug fixes aside)!

If you haven't got the source then yes, you can hack the bytecode and do things that way. But I'm pretty confident that isn't what's needed here :-)

Upvotes: 0

dotrc
dotrc

Reputation: 171

If you mean to kind of 'patch' the current behavior, then you'll need to copy the existing java file, update the method you want to override and place its .class ahead in the CLASSPATH.

Upvotes: 1

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181290

You need to subclass the class inside your JAR and then override the method. There is no way to "change" an existing method on an existing class in Java unless you change the source code and recompile it.

Upvotes: 1

Related Questions