2014-09-01 176 views
0

我認爲我的代碼有問題,以靜態方式或以非靜態方式調用(在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()); 
    } 
} 
+2

不是一個答案,但是 - 事實上你問這個問題應該讓你思考的設計。如果每個用法都與保存的實例連接,我看不出爲什麼isSameMonth應該是一個靜態方法。 – Deltharis 2014-09-01 11:34:17

+0

isSameMonth是靜態的,因爲我在getIstance中調用它是一個靜態方法。 但你說得對,我可以改變它:\t \t if(timesheet == null ||!timesheet.isSameMonth())並把isSameMonth設置爲非靜態。 你的回覆是最好的答案,謝謝:) – Accollativo 2014-09-01 11:42:52

+0

如果你的回覆是答案我會接受的 – Accollativo 2014-09-01 14:01:34

回答

1

,你問這個問題應該讓你思考設計的事實。如果每個用法都與保存的實例連接,我看不出爲什麼isSameMonth應該是一個靜態方法。

沒有嚴格的答案,主題中的問題,但顯然它幫助

2

它仍然可以正常工作,但習慣上是指通過類名靜態方法:

Timesheet.isSameMonth()

這使得清楚的人讀取喲你正在調用一個靜態方法的代碼。

1

不需要改變你的代碼,除了方法調用風格Timesheet.isSameMonth()

由於這是一個靜態方法,所以方便地調用方法的樣式是使用Class name而不是實例變量。

否則,閱讀代碼的人可能會認爲它是實例方法。這就是IDE爲了讓大家生活變得輕鬆的建議。

1

timesheet不是局部變量,它是類的靜態字段。而且您的IDE建議您將timesheet.isSameMonth()更改爲Timesheet.isSameMonth(),因爲該方法是靜態的,最好以該靜態方式訪問它。

如果timesheet不會是一成不變的,你就已經得到另一個編譯錯誤說,靜態isSameMonth()不能訪問非靜態變量。

訪問一個靜態方法的工作方式是:通過類名和通過實例引用,但會生成相同的代碼。即使基準是null你甚至可以訪問靜態方法:

Runtime r = null; 
r.getRuntime(); // This works even though r is null 
+0

但是,如果我打電話Timesheet.isSameMonth()我使用Gson對象,我傳遞給Timesheet.setIstance(gson.fromJson(json,Timesheet.class)); ? – Accollativo 2014-09-01 11:32:55

+0

編輯我的答案。 'timesheet.isSameMonth()'和'Timesheet.isSameMonth()'在生成的字節碼中是相同的。 – icza 2014-09-01 11:36:14

相關問題