如何避免儿童重复构造函数 [英] how to avoid repetitive constructor in children

查看:79
本文介绍了如何避免儿童重复构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个父类,其构造函数为:

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;
    }

现在在children类中,我有类似的构造函数:

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();
        }
...

问题是我有很多孩子上课了吗来自AbstractResource,我必须再次使用'Authorization'和'Helper'编写类似的构造函数。有什么办法可以避免重复编码?

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?

对不起,更新了我的代码,是的,我可以在每个子类中调用super(..),但是仍然在每个构造函数中我都注入了所有这些参数,auth和帮助者,只是想知道是否有一种方法可以简化该过程

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

推荐答案

除非我对此有所遗漏,否则有一个简单的方法

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

在子类的构造函数中,第一行应为: super(authorization,helper)

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

编辑:作者已编辑了问题,因此该解决方案不再适用。

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

这篇关于如何避免儿童重复构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆