我认为我的代码有问题,以静态方式或以非静态方式调用(在setIstance
中)方法isSameMonth()
是否相同?
编译器建议我更改:timesheet.isSameMonth()
到Timesheet.isSameMonth()
我认为不可以,因为我想传递局部变量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应该是静态方法。
并非严格回答该主题中的问题,但显然有帮助