【问题标题】:Java Call a Constructor from Another Constructor Without Immediately Having the ParametersJava 从另一个构造函数调用构造函数而不立即具有参数
【发布时间】:2015-09-22 06:12:51
【问题描述】:

有没有什么方法可以从另一个构造函数调用一个构造函数而不立即获得它的参数?

我在尝试为我的 SimpleDate 类创建一个构造函数时遇到了这个问题,该类接受一个毫秒时间参数并使用另一个构造函数来创建类(下面的代码)。我遇到的问题是构造函数调用必须在第一行,但我并没有真正看到要在正确的时间获得Calendar 实例,而无需先在前一行设置时间(以毫秒为单位)。我没有看到如何在一行上做到这一点,因为setTimeInMillis 是一个 void 方法,我认为在调用方法后不可能返回值(如果它比我非常想知道如何作为好吧)。我意识到这整件事并不是完全必要的,但我确实想知道这是否可行,如果可行,我会怎么做。

        public SimpleDate(long timeMillis) {
            this(Calendar.getInstance().setTimeInMillis(timeMillis));//Obviously this doesn't work because setTimeInMillis is a void method
        }

        public SimpleDate(Calendar calendar) {
            this.year = calendar.get(Calendar.YEAR);
            this.month = calendar.get(Calendar.MONTH) + 1;
            this.day = calendar.get(Calendar.DAY_OF_MONTH);

            this.hour = calendar.get(Calendar.HOUR_OF_DAY);
            this.minute = calendar.get(Calendar.MINUTE);
            this.second = calendar.get(Calendar.SECOND);
        }

【问题讨论】:

    标签: java methods constructor calendar


    【解决方案1】:

    您可以通过调用类上的静态方法为您执行必要的转换来做到这一点。

    protected static Calendar getCalendarForMillis(long millis) {
        Calender ret = Calendar.getInstance();
        ret.setTimeInMillis(millis);
        return ret;
    }
    
    public SimpleDate(long millis) {
        this(getCalendarForMillis(millis));
    }
    

    你的问题的答案是否定的:如果参数在构造函数的顶部没有准备好,你不能在初始化的后期调用另一个构造函数。这就是为什么你必须做一些静态方法解决方法。

    【讨论】:

    • 谢谢!我想这不是我希望的那样漂亮的解决方案,但它工作得很好。
    【解决方案2】:

    您想要的只是重用从Calendar 实例创建字段的代码,并能够首先将一个构造函数的long millis 参数转换为Calendar 实例。

    如果您将 Calendar -> your fields 代码直接放入一个构造函数中,则意味着要重用它,您必须在另一个构造函数的第一行调用该构造函数。这有点笨拙,因为它迫使您使用单独的静态 millis -> Calendar 方法,这可能不会在其他地方使用。

    更灵活、更简洁的解决方案是将Calendar -> your fields 代码放在单独的方法中,然后从两个构造函数中调用它:

    public SimpleDate(Calendar calendar) {
      setDateFields(calendar);        
    }
    
    public SimpleDate(long millis) {
      Calendar calendar = Calendar.getInstance();
      calendar.setTimeInMillis(millis);
      setDateFields(calendar);      
    }
    
    private void setDateFields(Calendar calendar) {
      this.year = calendar.get(Calendar.YEAR);
      this.month = calendar.get(Calendar.MONTH);
      this.day = calendar.get(Calendar.DAY_OF_MONTH);
      this.hour = calendar.get(Calendar.HOUR_OF_DAY);
      this.minute = calendar.get(Calendar.MINUTE);
      this.second = calendar.get(Calendar.SECOND);
    }
    

    这样,您可以在任一构造函数中调用方法之前进行设置或任何其他您喜欢的操作,我相信这是您真正想要的。

    【讨论】:

    • 我知道发布有更简单的方法可以做到这一点的问题,我真的只是想知道是否可以这样做。你的方法确实达到了同样的效果。
    猜你喜欢
    • 2011-03-24
    • 2015-07-02
    • 1970-01-01
    • 2016-07-03
    • 1970-01-01
    • 2010-09-22
    • 2010-12-15
    相关资源
    最近更新 更多