问题
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.
回答1:
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.
回答2:
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();
}
}
回答3:
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.
来源:https://stackoverflow.com/questions/39579166/how-to-extend-a-final-classreflection-javassist