class DataObject
{
String attr1;
String attr2;
String attr3;
// getters of three fields(getAttr1(),getAttr2() and getAttr3())
// setters of three fields(setAttr1(),setAttr2() and setAttr3())
}
List<DataObject> result = null;//Output List of objects of 'DataObject' class
List<DataObject> dataObjectList; // Input List of objects of 'DataObject'class.
Predicate<DataObject> first= e -> e.getAttr1().equals("Value1_1");
result = dataObjectList.stream().filter(first).collect(Collectors.toList());
我想根据运行时的条件过滤对象列表(这里的条件是 attr1 = "Value1_1")。我的问题是我只会在运行时获取方法名称(可以是 getAttr1() 或 getAttr2() 或 getAttr3() 或任何其他函数)。我使用反射来解决这个场景。
Class<?> cls = Class.forName("com.example.java.DataObject");
Class<?> noparams[] = {};
Method method = cls.getDeclaredMethod("getAttr1", noparams);
Predicate<DataObject> first= e -> method.equals("Value1_1");
但是代码不会给出所需的结果。请根据反射(reflection)纠正我的代码。另外请给我任何替代解决方案。
最佳答案
您必须实际调用该方法才能使用 Method#invoke()
获取结果。方法。现在,您只是比较 Method
对象。将其更改为:
Predicate<DataObject> first= e -> method.invoke(e).equals("Value1_1");
但这确实是一种奇怪的方式。我确信如果您能展示您到底想要做什么,还可以有其他方法。
关于java - java 中带有反射的谓词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29506571/