1

How to dynamically add a method to a Spring bean? (Cannot edit bean sources statically)

J.J. Beam
  • 2,612
  • 2
  • 26
  • 55

1 Answers1

1

How to dynamically add a method to a Spring bean?

Bean is an object. You dont need to add anything to an already instantiated Object.

I am guessing, you meant to ask "How to dynamically add a method to a class which I dont have edit access"

Answer is,

  1. You probably dont need to add anything to that class , you probably can extend it and add your method and instantiate it and use that bean instead of the original bean
  2. If you really have to edit class at runtime

    Either look at

    a) Reflection (https://www.oracle.com/technical-resources/articles/java/javareflection.html)

    Or

    b) Bytecode Manipulation (Are there alternatives to cglib?)

so-random-dude
  • 15,277
  • 10
  • 68
  • 113
  • 1
    Yes, it was a tricky interview question to me. I should have answer to him: "the same way as into any POJO in any program" but I didn't realize ( – J.J. Beam Dec 14 '19 at 00:34