2017-03-17 82 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。这是复杂和缓慢的,并超出了这个答案的范围来进一步解释。