How to extend a final class?(Reflection, Javassist)

橙三吉。 提交于 2019-12-11 05:49:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!