流内部的Java反射';s过滤器
我有一个Java POJO:流内部的Java反射';s过滤器,java,generics,reflection,java-8,java-stream,Java,Generics,Reflection,Java 8,Java Stream,我有一个Java POJO: public class Event { private String id; private String name; private Long time; } 我创建的一个简单过滤方法是: public static List<Event> simpleFilter(List<Event> eventList, String value) { return eventList.stream().filte
public class Event {
private String id;
private String name;
private Long time;
}
我创建的一个简单过滤方法是:
public static List<Event> simpleFilter(List<Event> eventList, String value) {
return eventList.stream().filter(Event -> Event.getName().equals(value)).collect(Collectors.toList());
}
来电者看起来像:
//events is List<Event>
//getName is the method in Event on which I want to filter
//e2 is value which I want to filter
genericStringFilterOnList(events, Event.class, "getName", "e2")
但有了这个,我就有了NPE
}).collect(Collectors.toList());
您能帮我创建一个泛型方法吗?该方法可以为任何POJO的列表调用,并且过滤器可以应用于其任何字符串类型的方法?调用应该发生在项目上,而不是类本身上。该方法有两个参数:
-从中调用基础方法的对象obj
-用于方法调用的参数args
return c.getMethod(methodName, null).invoke(c).equals(value);
。。致:
return c.getMethod(methodName, null).invoke(m).equals(value);
混淆源于一个字母的变量名(参见下面的解决方案)
整个解决方案应简化。您不希望通过对流管道中存在的每个对象的反射来提取完全相同的
方法。首先提取方法
并重新使用它:
static <T> List<T> genericStringFilterOnList(List<T> list, Class<T> clazz, String method, String value) {
try {
// reflection invoked just once
Method method = clazz.getMethod(method, null);
// now streaming of the n items
return list.stream().filter(item -> {
try {
return value.equals(method.invoke(item));
} catch (IllegalAccessException | InvocationTargetException e) {}
return false;
}).collect(Collectors.toList());
} catch (NoSuchMethodException e) {}
return Collections.emptyList();
}
静态列表genericstringfilternist(列表列表、类clazz、字符串方法、字符串值){
试一试{
//反射只调用一次
方法Method=clazz.getMethod(方法,null);
//现在,n个项目的流式处理
返回列表.stream().filter(项->{
试试{
返回值.equals(方法.invoke(项));
}catch(IllegalAccessException | InvocationTargetException e){}
返回false;
}).collect(Collectors.toList());
}catch(NoSuchMethodException){}
返回集合。emptyList();
}
(超出此问题的范围):请注意,被调用的方法返回null
的概率高于传递的value
的概率,因此我选择value.equals(method.invoke(item))
。当两个值都是null
要比较时,可能需要添加一些额外的比较条件
return c.getMethod(methodName, null).invoke(c).equals(value);
return c.getMethod(methodName, null).invoke(m).equals(value);
static <T> List<T> genericStringFilterOnList(List<T> list, Class<T> clazz, String method, String value) {
try {
// reflection invoked just once
Method method = clazz.getMethod(method, null);
// now streaming of the n items
return list.stream().filter(item -> {
try {
return value.equals(method.invoke(item));
} catch (IllegalAccessException | InvocationTargetException e) {}
return false;
}).collect(Collectors.toList());
} catch (NoSuchMethodException e) {}
return Collections.emptyList();
}