I would like to get the fields of Generic class "T" using reflection in order to build a basic Filter Predicate from all the Type=String fields.
Using T.getFields doesn't seem to be an option which is what I assumed I would use.
This class is to be used in a JTextField which I intend to use to search over various objects. I will pass it additional search criteria, but for basic functionality I want to default to searching all String fields.
public class SearchListener<T,C extends Collection<T>> implements DocumentListener {
private JList jlist;
private C staticCollection;
private List<Predicate<T>> predicateList = new ArrayList<>();
//get the String fields, and build Predicate from them.. add to predicateList.
public SearchListener(JList jlist, List<Predicate<T>> predicateList, C collection) {
this.jlist = jlist;
this.staticCollection=collection;
this.predicateList=predicateList;
}
@Override
public void insertUpdate(DocumentEvent de) {
filter();
}
@Override
public void removeUpdate(DocumentEvent de) {
filter();
}
@Override
public void changedUpdate(DocumentEvent de) {
filter();
}
private void filter() {
jlist.setModel((ListModel)staticCollection);
C items = (C) jlist.getModel();
Stream<T> itemStream = items.stream().filter(x ->{
Stream<Predicate<T>> predicateStream= predicateList.stream();
return predicateStream.map(predicate -> predicate.test(x)).reduce((a,b)->a && b).get();
});
ArrayList<T> collect = itemStream.collect(Collectors.toCollection(ArrayList::new));
C name = (C)collect;
jlist.setModel((ListModel)name);
}
}
Aucun commentaire:
Enregistrer un commentaire