我有一对有三对Date
字段的课程。
public static final class Filter {
private final Date startDateFrom;
private final Date startDateTo;
private final Date endDateFrom;
private final Date endDateTo;
private final Date regDateFrom;
private final Date regDateTo;
public Filter(Date startDateFrom, Date startDateTo,
Date endDateFrom, Date endDateTo,
Date regDateFrom, Date regDateTo) {
this.startDateFrom = startDateFrom;
this.startDateTo = startDateTo;
this.endDateFrom = endDateFrom;
this.endDateTo = endDateTo;
this.regDateFrom = regDateFrom;
this.regDateTo = regDateTo;
}
}
因此,我需要检查至少有一对没有null
个日期,并检查DateFrom
是否在所有非空日期之前或等于DateTo
。
我这是为了检查是否至少有一对:
public boolean allDatesMissing() {
if (startDateFrom != null && startDateTo != null) {
return false;
} else if (endDateFrom != null && endDateTo != null) {
return false;
} else if (regDateFrom != null && regDateTo != null) {
return false;
}
return true;
}
这是检查fromDate
之前的toDate
:
public void checkDates(Date from, Date to) throws RequestException{
if (from != null) {
if (to != null) {
if (from.after(to)) {
throw new MyException(INCORRECT_DATES_PERIOD);
}
} else {
throw new MyException(MISSING_PARAMETER);
}
} else if (to != null){
throw new MyException(MISSING_PARAMETER);
}
}
有没有更简单的方法来做同样的事情?
答案 0 :(得分:1)
你已经将Filter类声明为static ..然后它应该是一个内部类..
package demo;
import java.util.Date;
public class FilterDemo {
public static void main(String[] args) throws Exception {
Filter f = new Filter(new Date(2017, 01, 01), new Date(2017, 02, 01),
null, null, null, null);
}
public static final class Filter {
private final Date startDateFrom;
private final Date startDateTo;
private final Date endDateFrom;
private final Date endDateTo;
private final Date regDateFrom;
private final Date regDateTo;
// dateCounter will maintain the count of correct date pair
public static int dateCount = 0;
public Filter(Date startDateFrom, Date startDateTo, Date endDateFrom,
Date endDateTo, Date regDateFrom, Date regDateTo)
throws Exception {
this.startDateFrom = startDateFrom;
this.startDateTo = startDateTo;
isExist(startDateFrom, startDateTo);
this.endDateFrom = endDateFrom;
this.endDateTo = endDateTo;
isExist(endDateFrom, endDateTo);
this.regDateFrom = regDateFrom;
this.regDateTo = regDateTo;
isExist(regDateFrom, regDateTo);
// throw exception after initializing 3 pair,if count is still 0
if (dateCount == 0)
throw new Exception("All pairs are null");
}
public static void isExist(Date from, Date to) throws Exception {
if (from != null && to != null) {
checkDates(from, to);
}
}
public static void checkDates(Date from, Date to) throws Exception {
if (from.getTime() > to.getTime()) {
throw new Exception("INCORRECT_DATES_PERIOD");
}
//increase dateCount if date pair is correct
dateCount++;
}
}
}