Can Java Annotations help me with this?

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

    Why are you doing this? Are you attempting to avoid having a constructor with many arguments (using setters then calling init) or are you avoiding having many constructors that all have similar arguments? If this is the case, you can use a builder pattern.

    public class Foo {
    int a, b, c, d, e;
    Foo(int a, int b, int c, int d, int e) { this.a=a; /*etc*/ }
    }
    
    public class FooBuilder {
    int a,b,c,d,e;
    FooBuilder A(int a) { this.a=a; return this;}
    FooBuilder B(int b) { this.b=b; return this;}
    //etc
    Foo create(){ return new Foo(a,b,c,d,e);
    }
    

    If this doesn't work, I'd suggest looking into AOP. I'd mark the methods that must have init() called already with an annotation [perhaps @requires('init') or the like] and make you AOP framework insert the proper code. Be careful that multiple init's either don't have side effects or that you do proper synchronization on your has_init_been_called state.

提交回复
热议问题