Java - creating a subclass dynamically

前端 未结 3 1901
情话喂你
情话喂你 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:34

    One library that I'm particularly fond of may be used here; Bytebuddy.

    Example taken directly from the landing page:

    Class dynamicType = new ByteBuddy()
      .subclass(Object.class)
      .method(ElementMatchers.named("toString"))
      .intercept(FixedValue.value("Hello World!"))
      .make()
      .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
      .getLoaded();
    

    It's incredibly flexible and definitely worth checking out if you'd like to keep your hair, I personally find heavy usage of javassist can get quite ugly and messy at times, bytebuddy feels like a well needed breath of fresh air!

    Rafael Winterhalter is also active on StackOverflow which makes finding out anything you're unsure of a breeze.

    Edit: my apology for necroposting. Landed here when a friend linked the question and forgot to check the date.

提交回复
热议问题