I have a .JAR file and it has tons of classes. One, that I need is set as final, so I cannot extend it. There is one method, that I basically have to extend and fix, otherwise everything breaks. How can I do that? I know Reflection and Javassist can be used for this, but I have no idea how. Any other tool is also acceptable, as long as it works.
Asked
Active
Viewed 3,599 times
2
-
1Have a look over http://stackoverflow.com/questions/13294629/how-to-extend-a-final-class-in-java – Ankit Tripathi Sep 19 '16 at 17:53
-
Seen it, there is no example. I know it's not possible using Java normally, but I still need to get it done – Gintas_ Sep 19 '16 at 17:54
3 Answers
4
You can use a wrapper around the Final class for example and extend the functionality,for example :
public class YourClass {
private FinalClass finalClass;
public YourClass {
finalClass = new FinalClass():
}
public void yourMethod() {
finalClass.methodInFinalClass();
}
}

Ankit Tripathi
- 405
- 4
- 13
3
You can't use reflection to modify existing class definitions.
If the licence of that JAR allows you to, I would suggest a different solution: decompile that one class; drop the final keyword; and rebuild class and JAR file.
That is the only robust way to solve your problem.

GhostCat
- 137,827
- 25
- 176
- 248
-
Which one did you try? And just for the record - we are not talking open source, where you could simply download the source? – GhostCat Sep 19 '16 at 17:52
-
Using JD-GUI, Luyten. Actually, it's a little bit of white-hat hacking :) – Gintas_ Sep 19 '16 at 17:53
-
One other thought: do you know about the **implementation** of that class? What I mean is: would there be a chance to completely replace it with your own code? Or are the "real" functions in that class important to you? – GhostCat Sep 19 '16 at 17:56
-
Thought about it. But there is a signature algorithm in that class, I thought about copy pasting it in my code, but decompiler messes it up real good. Now that I looked closer at it, I think my problem is quite different - I need to actually remove a method from that class and it should work fine. Because now I'm getting NoClassDefFoundError for some random class. I think I will create a new StackOverflow post, it will get too off-topic – Gintas_ Sep 19 '16 at 18:00
-
@Gintas_ Just use the Krakatau disassembler. That can handle anything, even classes which are impossible to decompile. If you're feeling brave, you can also use a hex editor. Removing the final flag is a single bit flip at a fixed offset, so it's easy to do in a hex editor. – Antimony Sep 20 '16 at 02:07
0
Final classes are marked final for a reason, so ideally you should not try to modify the class. You should consider moving to other APIs or write your own solution class for your case.

kazzaki
- 64
- 3