好的,我一直在玩弄优秀的 JodaTime 库,试图实现一个通用案例零售/财政 (4-5-4) 日历。我已经找到了我公司的具体案例,但一般案例(主要是确定年初和闰年)是致命的;例如,有一组日期,两个会计年度(通常为 364 天)将在 1 个 ISO 年开始。
在确定年开始规则的过程中,我最终得到了一个抽象类和几个具体类来确定年开始,根据它们落在 ISO 闰日的哪一侧。
(精简)抽象类:
private static abstract class SimpleFiscalYearEndPattern implements FiscalYearEndPattern {
protected final int leapYearCountOffset;
protected final int doomsdayOffset;
private final int startingDayOfWeek;
private final int yearOffset;
private final long millisFromEpochToFiscalYearStart;
private final long millisElapsedToEpochDividedByTwo;
/**
* Restricted constructor
* @param fiscalYear
* @param startingOn
* @param inFirstWeek
*/
protected SimpleFiscalYearEndPattern(final int fiscalYear, final LocalDate startingOn, final MonthDay inFirstWeek) {
this.yearOffset = fiscalYear - startingOn.getYear();
this.doomsdayOffset = getDoomsdayOffset(inFirstWeek);
this.startingDayOfWeek = startingOn.getDayOfWeek();
final int startingDoomsday = getDoomsdayOffset(new MonthDay(startingOn, REFERENCE_CHRONOLOGY));
// If the starting doomsday is a later day-of-week, it needs to become negative.
this.leapYearCountOffset = calculateLeapYearCountOffset(startingDoomsday : doomsdayOffset, doomsdayOffset);
final int leapYearsBefore = getPreviousLeapYears(fiscalYearBeforeEpoch);
}
}
(缩减)具体课程(适用于 1/7 - 2/28 范围内的日期):
private static final class BeforeLeapYearEndPattern extends SimpleFiscalYearEndPattern {
private static final int FIRST_YEAR_LEAP_YEAR_OFFSET = -1;
private BeforeLeapYearEndPattern(final int fiscalYear, final LocalDate startingOn, final MonthDay onOrBefore) {
super(fiscalYear, startingOn, onOrBefore);
}
public static final BeforeLeapYearEndPattern create(final int fiscalYear, final LocalDate startingOn, final MonthDay onOrBefore) {
return new BeforeLeapYearEndPattern(fiscalYear, startingOn, onOrBefore);
}
/* (non-Javadoc)
* @see ext.site.time.chrono.FiscalYearEndPatternBuilder.SimpleFiscalYearEndPattern#getPreviousLeapYears(int)
*/
@Override
protected int getPreviousLeapYears(final int isoYear) {
// Formula gets count of leap years, including current, so subtract a year first.
final int previousYear = isoYear - 1;
// If the doomsday offset is -1, then the first year is a leap year.
return (previousYear + leapYearCountOffset + (previousYear / 4) - (previousYear / 100) + (previousYear / 400)) / 7 + (leapYearCountOffset == FIRST_YEAR_LEAP_YEAR_OFFSET ? 1 : 0);
}
如果您注意到,我使用leapYearCountOffset
了在抽象超类 in 中定义(作为最终变量)的 ,getPreviousLeapYears()
然后从超类构造函数中调用它。我不想在超类构造函数中重复这个公式——它对于 3/1-12/31 范围内的日期是不同的;我也不想将实例变量放在具体的子类中 - 其他计算仍然需要leapYearCountOffset
。
问题是:leapYearCountOffset
从构造函数调用(子类)方法时的状态是什么?它是否以任何方式得到保证,或者编译器会随心所欲地改变它?我怎么能测试它来找出答案呢?我已经知道编译器可以自由地重新安排一些语句,但是(可能吗?)这会发生在这里吗?