我認爲我的代碼有問題,以靜態方式或以非靜態方式調用(在setIstance
中)方法isSameMonth()
是否一樣? 編譯器建議我改變:timesheet.isSameMonth()
到Timesheet.isSameMonth()
在java中的靜態方法,我可以以非靜態方式訪問靜態方法嗎?
我覺得沒什麼,因爲我想通過當地變量timesheet
,是同樣的事情,或者我應該修改我的密碼?
時間表類:
static private Timesheet timesheet;
static public Timesheet getIstance()
{
if (timesheet == null || !Timesheet.isSameMonth())
{
timesheet = null;
timesheet = new Timesheet();
}
return timesheet;
}
static public void setIstance(Timesheet timesheet)
{
if (timesheet != null && timesheet.isSameMonth())
{
Timesheet.timesheet = timesheet;
}
}
public static boolean isSameMonth()
{
Date now = new Date();
Calendar calendarNow = Calendar.getInstance();
calendarNow.setTime(now);
Date firstDay = timesheet.days[0];
Calendar calendarFirstDay = Calendar.getInstance();
calendarFirstDay.setTime(firstDay);
if (calendarNow.get(Calendar.MONTH) == calendarFirstDay.get(Calendar.MONTH))
{
return true;
}
return false;
}
從外面我做這樣的判斷:
Gson gson = new Gson();
String json = sharedPrefs.getString("timesheet", "");
if (!json.isEmpty())
{
try
{
Timesheet timesheet = Timesheet.getIstance();
if (timesheet.getDay(0)==null)
{
Timesheet.setIstance(gson.fromJson(json, Timesheet.class));
}
refreshWidget(timesheet, context, allWidgetIds, intent.getAction());
}
catch (Exception e)
{
Log.e(TAG_LOG, e.toString());
}
}
不是一個答案,但是 - 事實上你問這個問題應該讓你思考的設計。如果每個用法都與保存的實例連接,我看不出爲什麼isSameMonth應該是一個靜態方法。 – Deltharis 2014-09-01 11:34:17
isSameMonth是靜態的,因爲我在getIstance中調用它是一個靜態方法。 但你說得對,我可以改變它:\t \t if(timesheet == null ||!timesheet.isSameMonth())並把isSameMonth設置爲非靜態。 你的回覆是最好的答案,謝謝:) – Accollativo 2014-09-01 11:42:52
如果你的回覆是答案我會接受的 – Accollativo 2014-09-01 14:01:34