【发布时间】:2014-09-01 11:26:55
【问题描述】:
我认为我的代码有问题,以静态方式或非静态方式调用(在setIstance 中)方法isSameMonth() 是否相同?
编译器建议我更改:timesheet.isSameMonth() 到 Timesheet.isSameMonth()
我认为不是,因为我想传递 local 变量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 应该是静态方法。
-
isSameMonth 是静态的,因为我在 getIstance 中将其称为静态方法。但你说得对,我可以将其更改为: if (timesheet == null || !timesheet.isSameMonth()) 并将 isSameMonth 设置为非静态。你的回复是最好的答案,谢谢:)
-
如果你的回复是一个答案,我会接受它
-
如果你有这样的感觉 - 完成了。
标签: java static static-methods