2013-04-30 103 views
1

我有許多類(至少45個)。每個人都有自己的方法來驗證所有類中重複的內容,所以我在所有類中重複了代碼。我想要一個方法並從所有類中調用它。Intellij Idea和/或Eclipse中的方法重構

如果有下面的代碼就知道如果移動設備連接到服務器

private boolean isMobileDevice(HttpServletRequest request) { 
    String userAgent = request.getHeader("user-agent"); 
    return userAgent.indexOf("Windows CE") != -1; 
} 

正如之前所說,重複在許多類這種方法

是在IntelliJ IDEA的可能和/或Eclipse來做那個重構?以及我如何執行重構?

+0

是否有可能看一些示例代碼? – 2013-05-02 05:16:07

+0

當然,這是可能的,我將我的重複功能添加到我的問題。 – igarcia 2013-05-02 15:18:41

回答

0
private boolean isMobileDevice(HttpServletRequest request) { 
     String userAgent = request.getHeader("user-agent"); 
     return userAgent.indexOf("Windows CE") != -1; 
} 

我敢打賭,我的Eclipse會提醒我,這個方法可以聲明爲static,因爲它不使用封閉類的任何領域 - 這樣的方法應該被聲明爲靜態的,讓你知道它是不是本質上需要在封閉類中,如果有一個原因(有45個方法取代一個是THE REASON),你可以將它移動到其他類,並且只是將它稱爲公共或包裝方法。

編輯:做:The method isMobileDevice(HttpServletRequest) from the type Test can be declared as static

所以:

將其複製到其他一些類,使之public static boolean isMobileDevice(HttpServletRequest request),並在每類的地方是private boolean使用。

就是這樣,但我沒有看到和自動重構的方式。

0

用Intellij你可以試試"Refactor" > "Find and Replace Code Duplicates..."。 它將通過靜態函數替換重複的代碼。