日历(GregorianCalendar).complete()方法不可见?

时间:2016-09-23 00:23:35

标签: java calendar

所以我读了几个不同的主题,但似乎没有一个直接解决我如何解决我的问题。我尝试创建CalendarGregorian),然后使用.complete()方法,以便在我的课程中使用此(Paycheck)类我可以找到相对dates并从这些日期创建new Calendar(s)以确定支付的工资和欠工资。但是,它告诉我.complete() .computeTime().computeFields()都不可见。

从我读过的内容来看,这似乎是因为它们是受保护的方法,即使我import the java.util为它们,我也无法访问它们,因为该类不在我的包中。我如何得到这个,以便我可以调用.complete()方法?

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;


public class Paycheck {
    //fields
    protected double grossAmount;
    protected Calendar paymentDate;
    protected Calendar payPeriodStart;

    public Paycheck(double grossAmount, int iYear, int iMonth, int iDay, int sYear, int sMonth, int sDay) {
        this.grossAmount = grossAmount;

        TimeZone tz1 = TimeZone.getTimeZone("America/Chicago");
        this.paymentDate = new GregorianCalendar(iYear, iMonth, iDay);
        this.paymentDate.setTimeZone(tz1);
        this.paymentDate.complete(); //says "method not visible"


        this.payPeriodStart = new GregorianCalendar(sYear, sMonth, sDay);
        this.payPeriodStart.setTimeZone(tz1);

    }

2 个答案:

答案 0 :(得分:0)

在你写的comment中:

  

我不关心实际的时间,我只是想让它给我一个日期,以便我可以确定每周一天(根据各州法律来说很重要)。

这很容易做到,并且不需要调用内部方法。

Calendar cal = new GregorianCalendar(2016, Calendar.SEPTEMBER, 22);
cal.setTimeZone(TimeZone.getTimeZone("America/Chicago"));
System.out.println("Day of week (1=Sun, ..., 7=Sat): " + cal.get(Calendar.DAY_OF_WEEK));

输出

Day of week (1=Sun, ..., 7=Sat): 5

输出为5,因为今天是Thu 9/22/2016,而且这是给定的日期。

答案 1 :(得分:-1)

让我们比较打字工作:

this.paymentDate = new GregorianCalendar(iYear, iMonth, iDay);
this.paymentDate.complete(); // Why do you need to call this one?

vs具有相同效果的代码

this.paymentDate = new GregorianCalendar(iYear, iMonth, iDay, 0, 0, 0);
// constructor taking extra hours, minutes, seconds ----------^

所以你为什么尝试几乎不可能调用受保护的方法

在某些情况下,数量非常有限,实际上需要调用受保护/私有方法,这可能是可能的。例示:

Class<GregorianCalendar> clazz=GregorianCalendar.class;
Method completeMethod = clazz.getDeclaredMethod("complete");
 // this does the trick if it doesn't throw security exceptions
completeMethod.setAccessible(true);
completeMethod.invoke(this.paymentDate);

请参阅AccesibleObject.setAccessible的Javadoc,Method来自AccessibleObject

相关问题