Can Java Annotations help me with this?

前端 未结 7 564
日久生厌
日久生厌 2021-01-13 14:52

I\'m wondering if there is a way to specify that a method gets called in advance of a class method. I know something like this should be posssible, since JUnit has before(),

7条回答
  •  别那么骄傲
    2021-01-13 15:20

    There is no direct way to do this in the java language. What you are seeing in JUnit is the framework making a decision about how to run the methods by calling the methods annotated with @Before first. It is very easy to find annotated methods and run them, but that is the responsibility of the caller.

    The problem you present is too simple to know the right way to a solution. AspectJ does address this need by manipulating the byte code (essentially calling the init() method when foo() is called by changing the bytecode to make that happen), but I can't imagine introducing that as a hack around a problem.

    If you can present an interface or a wrapper object to this class, you could do it that way. But I would suggest you post the ugly hack that got you into this situation in the first place in a separate question, and then post how your current hack solution requires that method calls be intercepted and why that is the case, and if there are better workarounds. That way we can help address the underlying need better.

提交回复
热议问题