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 :(得分:0)
这不是直接可行的,但是你可以尝试一些事情(从最简单到最难):
只需在代码中自行检查所有String类型方法。
在Item
中添加一个执行匹配的特殊方法,以便Item
类在匹配时自行决定。在这里,您需要手动检查所有字符串。
您可以向Item
添加一个方法,该方法返回将String作为函数返回的所有方法:
代码:
List<Supplier<String>> getAllStringMethods() {
return Arrays.asList(this::getComment, this::getTitle);
}
然后,您可以通过执行以下操作来一次检查所有字符串:
boolean match = item.getAllStrings().stream()
.map(Supplier::get)
.anyMatch(s -> s.matches("pattern"));
Item.class
以查找不带参数的所有方法并返回String
,然后逐个invoke
。这是复杂而缓慢的,超出了这个答案的范围,可以进一步解释。