search

Home  >  Q&A  >  body text

java - How to call a piece of code by default before calling static method?

I now have a tool class with static methods in it, dedicated to external calls.
Now we hope that before each call to these static methods, a method or code block that sets default parameters will be called.
It is similar to adding a static code block, but the static code block will only be executed once when the class is initialized, rather than executed every time the static method is called, which does not meet my requirements.

The basic solution is to add a static method to this tool class and make the settings I want in it, but in this case I have to add statements to call this method in all other static methods, because I have There are many static methods, there are already more than 30, and there will be more, so I want to be lazy and ask if there is a way to solve it?

Um. . As a supplementary explanation, my project framework is based on spring mvc. After reading the AOP in the comments, I went to Baidu and found that it may be able to meet my requirements. I am currently trying further.
If it were just pure java code, it would be difficult for me to solve this need even if I think about it.

淡淡烟草味淡淡烟草味2744 days ago920

reply all(8)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-06-12 09:27:34

    ....I’ll give you the virgin answer of SF,
    Don’t think about it, no...

    reply
    0
  • ringa_lee

    ringa_lee2017-06-12 09:27:34

    aop I really don’t know how to answer your question

    reply
    0
  • typecho

    typecho2017-06-12 09:27:34

    AOP

    reply
    0
  • 大家讲道理

    大家讲道理2017-06-12 09:27:34

    My SF virgin answer is also given to you, let’s find another solution

    reply
    0
  • 扔个三星炸死你

    扔个三星炸死你2017-06-12 09:27:34

    You shouldn’t use static.
    If it’s a singleton from the beginning,
    it can be initialized,

    Although static can define a block that is executed when a class is loaded,
    but it is generally not applicable,

    reply
    0
  • 滿天的星座

    滿天的星座2017-06-12 09:27:34

    Although it can also be implemented using derived classes, it will only be more troublesome and does not meet the goal of convenience and speed of the subject.
    Compared with various methods, it is faster to add a line of code to each static method.
    Just copy and paste the question, it will be quick.

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-06-12 09:27:34

    Use regular expressions to match the beginning of each method, and then insert the method you want

    reply
    0
  • 三叔

    三叔2017-06-12 09:27:34

    Just add a callback to the method parameter, for example, it was originally written like this: public static void doSomeThing(Object args1)
    Now it is written like this

    public static void doSomeThing(Object args1,MyCallback callback){
        callback.execute(theargs...);
        //do other things...
    }

    reply
    0
  • Cancelreply