如何从Java中的字符串访问对象属性?

时间:2019-06-07 17:23:29

标签: java class

我有一个字符串,告诉我应该使用哪些属性进行一些过滤。如何使用此String实际访问对象中的数据?

我有一个返回字符串列表的方法,该方法告诉我如何过滤对象列表。如:

String[] { "id=123", "name=foo" }

所以我的第一个想法是使用以下方法将String分成两部分: 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做到这一点?

2 个答案:

答案 0 :(得分:1)

此代码应该可以工作:

  //create the filter map
  Map<String, String> expectedFieldValueMap = new HashMap<>();
    for (String currentDataValue : input) {
        String[] keyValue = currentDataValue.split("=");
        String expectedField = keyValue[0];
        String expectedValue = keyValue[1];
        expectedFieldValueMap.put(expectedField, expectedValue);
    }

然后遍历输入对象列表(已使用具有id和name字段的Employee类,并准备了带有几个称为inputEmployeeList的Employee对象的测试数据列表,该对象正在被迭代),看看是否所有过滤器都通过反射了,尽管速度很慢,一种方式:

for (Employee e : inputEmployeeList) {
            try {
                boolean filterPassed = true;
                for (String expectedField : expectedFieldValueMap.keySet()) {
                    String expectedValue = expectedFieldValueMap.get(expectedField);

                    Field fieldData = e.getClass().getDeclaredField(expectedField);
                    fieldData.setAccessible(true);
                    if (!expectedValue.equals(fieldData.get(e))) {
                        filterPassed = false;
                        break;
                    }
                }

                if (filterPassed) {
                    System.out.println(e + " object passed the filter");
                }

            } catch (Exception any) {
                any.printStackTrace();
                // handle
            }
        }

答案 1 :(得分:1)

您可以使用反射来通过动态名称获取类的字段。

@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的评论-它运行缓慢且可能存在危险。

相关问题