我有一个字符串,它告诉我应该使用什么属性来进行一些过滤。如何使用这个字符串来实际访问对象中的数据?
我有一个返回字符串列表的方法,告诉我如何过滤对象列表。如:
字符串[] { "id=123", "name=foo"}
所以我的第一个想法是将字符串分成两部分:
filterString.split("=")
并使用字符串的第一部分(例如“id”)来标识要过滤的属性。
对于 JS 背景,我会这样做:
const attr = filterString.split('=')[0]; // grabs the "id" part from the string "id=123", for example
const filteredValue = filterString.split('=')[1]; // grabs the "123" part from the string "id=123", for example
items.filter(el => el[`${attr}`] === filteredValue) // returns an array with the items where the id == "123"
我怎样才能用 Java 做到这一点?
最佳答案
您可以使用反射通过动态名称获取类的字段。
@Test
void test() throws NoSuchFieldException, IllegalAccessException {
String[] filters = {"id=123", "name=foo"};
List<Item> list = newArrayList(new Item(123, "abc"), new Item(2, "foo"), new Item(123, "foo"));
Class<Item> itemClass = Item.class;
for (String filter : filters) {
String key = StringUtils.substringBefore(filter, "=");
String value = StringUtils.substringAfter(filter, "=");
Iterator<Item> iterator = list.iterator();
while (iterator.hasNext()) {
Item item = iterator.next();
Field field = itemClass.getDeclaredField(key);
field.setAccessible(true);
Object itemValue = field.get(item);
if (!value.equals(String.valueOf(itemValue))) {
iterator.remove();
}
}
}
assertEquals(1, list.size());
}
但我同意 sp00m 的评论 - 它很慢并且有潜在危险。
关于java - 如何从Java中的字符串访问对象属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56498803/