how to avoid repetitive constructor in children

你离开我真会死。 提交于 2019-12-11 01:46:55

问题


I have a parent class, which has constructor as:

    @Inject
    public AbstractResource(@Named("authorization") Authorization auth,
                            @Named("helper") Helper helper) {
        this.authorization = authorization;
        this.helper = helper;
    }

now in the children class, i have similar constructor:

public class MyResource extends AbstractResource {
        private Manager manager;

        @Inject
        public MyResource(@Named("authorization") Authorization auth,
                          @Named("helper") Helper helper) {
            super(auth, helper);
            this.manager = new Manager();
        }
...

Problem is I have tons of children class extend from AbstractResource, I have to write the similar constructor with 'Authorization' and 'Helper' again and agin. is there any way i can avoid the repetitive coding?

Sorry, updated my code, yes, i can call super(..) in each children class, but still in each constructor i have inject all those parameters, auth and helper, just wonder if there is a way to even simplify that


回答1:


You can create an object to hold all the arguments.

But other than that, no not really. This is what production DI code in Java actually looks like.




回答2:


Unless I'm missing something about this there is a simple solution by calling through to the parent's constructor.

In your child class's constructor the first line should be: super(authorization, helper)

EDIT: Author has edited his question so this solution is no longer applicable.



来源:https://stackoverflow.com/questions/35372707/how-to-avoid-repetitive-constructor-in-children

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!