Can Java Annotations help me with this?

前端 未结 7 570
日久生厌
日久生厌 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:25

    I assume that the problem here is as follows:

    1. You have a constructor that can partially build the object, but can't completely build it because of the way the class must be constructed. (I can't think of an example offhand.)
    2. So you need an init() method that will finish construction.
    3. So you want to have some kind of guarantee that init() will be called right after the constructor.

    My suggestion is to use a factory object or method. The simplest way is to make the constructor private, add a construct() method with the parameters of the constructor or something of that sort, and then have the construct() method both create the object and call init(), then return it.

提交回复
热议问题