for (SchemaRowRuleEo schemaRowRuleEo : schemaRowRuleList) { //获取行规则要素 String filterConditionList = schemaRowRuleEo.getFilterConditionList(); List<SchemaRowFilterCondition> schemaRowFilterConditions = JSONObject.parseArray(filterConditionList, SchemaRowFilterCondition.class); for (SchemaRowFilterCondition schemaRowFilterCondition : schemaRowFilterConditions) { String field = schemaRowFilterCondition.getField(); String camel = underlineToCamel(field); String key = schemaRowFilterCondition.getKey(); Field fieldsAndParentsField = fieldStream .filter(f -> StringUtils.equals(f.getName(), camel)) .findFirst() .orElseThrow(() -> new CustomException("大马猴来了", code)); Field f = object.getClass().getDeclaredField(camel); f.setAccessible(true); Object value = f.get(object); if (StringUtils.equals(key, value.toString()) && schemaRowRuleEo.getRowEditPermission()) { System.out.println("修改成功"); } else { throw new CustomException("大马猴来了", code); } } }优化这段java代码
时间: 2024-02-18 08:00:16 浏览: 87
GB/Z37085-2018工业通信网络行规第3-8部分:CC-Link系列功能安全通信行规标准
这段 Java 代码可以做以下优化:
1. 使用 Lambda 表达式简化代码,如使用 Lambda 表达式替换 for 循环。
2. 避免重复获取对象的属性 Field,可以将其缓存到一个 Map 中,以便多次使用。
3. 将一些重复的字符串提取成常量,避免代码中出现重复的字符串。
下面是优化后的代码:
```
private static final String CODE = "大马猴来了";
public void optimizeCode(Object object, List<SchemaRowRuleEo> schemaRowRuleList) throws NoSuchFieldException, IllegalAccessException {
Map<String, Field> fieldMap = Arrays.stream(object.getClass().getDeclaredFields())
.collect(Collectors.toMap(Field::getName, field -> {
field.setAccessible(true);
return field;
}));
for (SchemaRowRuleEo schemaRowRuleEo : schemaRowRuleList) {
String filterConditionList = schemaRowRuleEo.getFilterConditionList();
List<SchemaRowFilterCondition> schemaRowFilterConditions = JSONObject.parseArray(filterConditionList, SchemaRowFilterCondition.class);
for (SchemaRowFilterCondition schemaRowFilterCondition : schemaRowFilterConditions) {
String field = schemaRowFilterCondition.getField();
String camel = underlineToCamel(field);
String key = schemaRowFilterCondition.getKey();
Field fieldAndParentField = fieldMap.get(camel);
Object value = fieldAndParentField.get(object);
if (StringUtils.equals(key, value.toString()) && schemaRowRuleEo.getRowEditPermission()) {
System.out.println("修改成功");
} else {
throw new CustomException(CODE, CODE);
}
}
}
}
private static String underlineToCamel(String underline) {
StringBuilder result = new StringBuilder();
String[] words = StringUtils.split(underline, '_');
for (int i = 0; i < words.length; i++) {
String word = words[i];
if (i == 0) {
result.append(word);
} else {
result.append(StringUtils.capitalize(word));
}
}
return result.toString();
}
```
阅读全文