2013-05-26 87 views
1

我有一個以字符串表示形式存儲的方法列表 「com.company.project.service.service1Impl.method()」 「com.company.project .service.service2Impl.method()」Java:如何實現類似於eclipse package explorer的樹結構樹

....

全類/包簽名

什麼是實現一個樹狀結構,以顯示包/類最適合的方式/方法與eclipse package explorer類似嗎?

例如:

com 
    mycompany 
    myproject1 
     service 
     service1Impl 
      method1 
      method2 
     service2impl 
     controller 
      controllerImpl 
      method1 
      method2 
      controllerImpl2 
    myproject2 

注:

如果

不知道這會有所作爲,但我正打算到這個數據結構轉換成JSON在UI jQuery的樹,以顯示它。

在此先感謝。

回答

2

我將與具有以下參數的遞歸方法解決這個問題:

  • 含有字符串數組
  • 當前前綴
  • 當前深度
  • 的最大深度(因此它只需要計算一次)

我認爲最好的解釋方法是用實際的代碼:

import java.util.ArrayList; 

public class Test { 

    public static void main(String[] args) { 
     Test t = new Test(); 
     String s1 = "com.company.project.service.service1Impl.method()"; 
     String s2 = "com.company.project.service.service2Impl.method()"; 
     String s3 = "com.company.test.service.service1Impl.method()"; 
     String s4 = "com.company.test.service.service2Impl.method()"; 
     String[] strings = { s1, s2, s3, s4 }; 
     t.print(strings); 
    } 

    public void print(String[] strings) { 
     //calculate max depth 
     int maxDepth = 0; 
     for (String string : strings) { 
      int currentDepth = string.split("\\.").length; 
      if (currentDepth > maxDepth) { 
       maxDepth = currentDepth; 
      } 
     } 
     this.print(strings, "", 0, maxDepth); 
    } 

    public void print(String[] strings, String start, int currentDepth, 
      int maxDepth) { 
     if (currentDepth == maxDepth - 1) { 
      return; 
     } 
     String currentPrint = null; 
     ArrayList<String> candidates = new ArrayList<String>(); 

     // add candidates 
     for (String s : strings) { 
      if (!s.startsWith(start)) { 
       continue; 
      } 
      String[] split = s.split("\\."); 
      if (split.length - 1 < currentDepth) { 
       continue; 
      } 
      if (currentPrint == null) { 
       currentPrint = split[currentDepth]; 
       candidates.add(currentPrint); 
       continue; 
      } 
      if (!currentPrint.equals(split[currentDepth])) { 
       currentPrint = split[currentDepth]; 
       candidates.add(currentPrint); 
      } 
     } 

     // print depth+1 with candidates 
     currentDepth++; 
     for (String c : candidates) { 
      // print current level 
      this.printSpaces(currentDepth - 1); 
      System.out.println(c); 
      // we have to go deeper 
      this.print(strings, start + c + ".", currentDepth, maxDepth); 
     } 
    } 

    // print spaces 
    public void printSpaces(int max) { 
     for (int i = 0; i < max; i++) { 
      System.out.print(" "); 
     } 
    } 
} 

問我有關代碼的任何問題。

編輯:這當然只適用於方法列表是按字母順序排序的。所以如果情況並非如此,分類將是第一步。