你知道怎么用Idea抽取方法、創建class嗎?


liJ IDEA的快捷鍵是進行重構的利器,坊間盛傳,完全使用IDEA快捷鍵重構的代碼,是不需要寫測試用例保護的

 

本文就分享一個使用IDEA抽取方法及創建新的class的方法

工具/原料

 
  • IntelliJ IDEA

方法/步驟

 
  1.  

    先來一段需要重構的代碼:

     

    package chapter4;import java.util.ArrayList;

    import java.util.Arrays;

    import java.util.List;

    /**

    * Created by MyWorld on 2016/3/21.

    */

    public class RefactorOperate {

       public static void main(String[] args) {

           List<String> seasonList = new ArrayList<String>(Arrays.asList("Spring", "Summer", "Autumn", "Winter"));

           for (String season : seasonList) {

               System.out.println(season);

           }

           seasonList.add("Spring Rain");

           seasonList.add("vernal equinox");

           System.out.println("======================");

           for (String season : seasonList) {

               System.out.println(season);

           }

       }

    }

    你知道怎么用Idea抽取方法、創建class嗎?
  2.  

    先把重復的代碼中負責打印操作的代碼提到一個方法中

    操作:

    如下截圖所示,選中需要提取的代碼

    同時Ctrl+Alt+m

    在彈出的對話框中,填入將要新生成的方法的名字,此處我們取的方法名是print

    最后點“確定”

    你知道怎么用Idea抽取方法、創建class嗎?
  3.  

    現在馬上就可以看到 IDEA的一個方便、強大的功能了

    從自動檢測出類似代碼,並提示出來

    "IDEA has detected 1 code fragment in this file that can be replaced with a call  to extracted method. would you like to review and replace it "

    此處我們選“Yes”

    你知道怎么用Idea抽取方法、創建class嗎?
  4.  

    看看抽取方法后,現在代碼的情況:

     

    package chapter4;import java.util.ArrayList;

    import java.util.Arrays;

    import java.util.List;

    /**

    * Created by MyWorld on 2016/3/21.

    */

    public class RefactorOperate {

       public static void main(String[] args) {

           List<String> seasonList = new ArrayList<String>(Arrays.asList("Spring", "Summer", "Autumn", "Winter"));

           print(seasonList);

           seasonList.add("Spring Rain");

           seasonList.add("vernal equinox");

           System.out.println("======================");

           print(seasonList);

       }    private static void print(List<String> seasonList) {

           for (String season : seasonList) {

               System.out.println(season);

           }

       }

    }

    你知道怎么用Idea抽取方法、創建class嗎?
  5.  

    輸入“StringUtils utils=new StringUtils();”

    IDEA肯定會提示編譯不過。肯定不過了,因為Project中根本沒有這個class

     

    把鼠標放在報錯代碼上,同時按“Alt + Enter”

    在彈出的菜單中選中“Create Class 'StringUtils'”

    然后回車(當然,使用鼠標直接點擊也可以)

    你知道怎么用Idea抽取方法、創建class嗎?
  6.  

    在彈出的“Create Class StringUtils”對話框中,確認下Destination Package的位置

    此處,我們就話在這個package下,直接點“OK”

    新Class StringUtils就創建完成了!!

    你知道怎么用Idea抽取方法、創建class嗎?
    你知道怎么用Idea抽取方法、創建class嗎?
  7.  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM