2017-03-17 76 views
-1
Item searchByPattern(String pat) 
    { 

     for(Iterator iter = items.iterator(); iter.hasNext();) 
     { 
      Item item = (Item)iter.next(); 
      if ((xxxxxxxxxxxx).matches(".*"+pat+".*")) 
      { 
       return item; 
      } 
     } 
    } 

上面的代碼是從我的java程序類的一部分得到幾個方法的返回值在一個聲明中

public class Item 
{ 
    private String title; 
    private int playingTime; 
    private boolean gotIt; 
    private String comment; 

    /** 
    * Initialise the fields of the item. 
    */ 
    public Item(String theTitle, int time) 
    { 
     title = theTitle; 
     playingTime = time; 
     gotIt = true; 
     comment = ""; 
    } 

    public String getTitle() { 
     return title; 
    } 

    /** 
    * Enter a comment for this item. 
    */ 
    public void setComment(String comment) 
    { 
     this.comment = comment; 
    } 

    /** 
    * Return the comment for this item. 
    */ 
    public String getComment() 
    { 
     return comment; 
    } 

    /** 
    * Set the flag indicating whether we own this item. 
    */ 
    public void setOwn(boolean ownIt) 
    { 
     gotIt = ownIt; 
    } 

    /** 
    * Return information whether we own a copy of this item. 
    */ 
    public boolean getOwn() 
    { 
     return gotIt; 
    } 

    public int getPlayingTime() 
    { 
     return playingTime; 
    } 

    /** 
    * Print details about this item to the text terminal. 
    */ 
    public void print() 
    { 
     System.out.println("Title: " + title); 
     if(gotIt) { 
      System.out.println("Got it: Yes"); 
     } else { 
      System.out.println("Got it: No"); 
     } 
     System.out.println("Playing time: " + playingTime); 
     System.out.println("Comment: " + comment); 
    } 

} 

我想訪問所有從class Item,一旦返回值的方法它匹配Item searchByPattern中的語句,它將返回該對象。 我知道我可以通過or運算符來運行,如item.getTitle().matches(".*"+pat+".*") ||item.getComment().matches(".*"+pat+".*")||....... 但是可以通過使用(xxxxxxxxxx)中的方法獲得相同的結果嗎?

回答

0

這是不能直接做的,但有一些事情你可以嘗試(從易到難):

  1. 就自己去查所有的字符串類型的方法在你的代碼。

  2. Item中添加一個特殊的方法來匹配,所以Item類可以在匹配時自行決定。在這裏,您還需要手動檢查所有字符串。

  3. 你可以添加一個方法來Item返回返回一個字符串作爲函數的所有方法:

代碼:

List<Supplier<String>> getAllStringMethods() { 
     return Arrays.asList(this::getComment, this::getTitle); 
    } 

然後,您可以用它來檢查所有字符串一個在一次做:

boolean match = item.getAllStrings().stream() 
      .map(Supplier::get) 
      .anyMatch(s -> s.matches("pattern")); 
  1. 您可以使用Reflection來檢查Item.class以查找所有不採用參數的方法,然後分別返回String,然後返回invoke。這是複雜和緩慢的,並超出了這個答案的範圍來進一步解釋。