Java - creating a subclass dynamically

前端 未结 3 1792
情话喂你
情话喂你 2021-02-14 09:25

I\'d like to create a subclass programatically. I guess I have few options - Javassist, CGLib, BCEL, or ASM.

The use case is that one app\'s internals are class-oriented

3条回答
  •  旧巷少年郎
    2021-02-14 09:41

    Java Proxies may be able to do what you require - they essentially allow you to dynamically layer functionality on top of an object, as you can intercept any method calls to that object, and either handle them yourself or dispatch the method calls to the underlying class. Depending on what you are looking to do, it may be that you can get the same result as you would by creating a sub-class dynamically

    Oracle has a decent introduction on their website (the URL references Java version 1.4.2, but I don't think the behavior of this has changed in more recent versions). Here is a more concise example that gives a good flavor for what proxy code looks like.

    It is also possible to do things using direct byte code manipulation (as supported by the ASM framework) however I imagine using proxies would be a simpler approach.

提交回复
热议问题