首页 > 解决方案 > 使用 Apache PropertyUtils 在 protobuf 生成的类中获取嵌套列表对象的属性

问题描述

我有以下 protobuf 文件:

syntax = "proto3";

import "google/protobuf/timestamp.proto";

option cc_enable_arenas = true;

option java_package = "com.my.trial";
option java_outer_classname = "MyTrial";

message EventMsg
{
  Header header = 1;
}
message Header
{
  repeated RulePolicyGuid triggers = 1;
}
message RulePolicyGuid
{
  string rule_guid = 1;
  string policy_guid = 2;
}

我从中使用 protobuf-maven-plugin 库生成一个 java 类。我正在尝试使用 apache PropertyUtils 库访问生成的类的 rule_guid 属性,如下所示:

MyTrial.EventMsg eventMsg = MyTrial.EventMsg.newBuilder()
            .setHeader(header)
            .build();
List lst = (List) PropertyUtils.getNestedProperty(eventMsg,"header.triggersList.ruleGuid");
System.out.println(lst);

但我收到错误:

Exception in thread "main" java.lang.NoSuchMethodException: Unknown property 'ruleGuid' on class 'class java.util.Collections$UnmodifiableRandomAccessList'
    at org.apache.commons.beanutils.PropertyUtilsBean.getSimpleProperty(PropertyUtilsBean.java:1269)
    at org.apache.commons.beanutils.PropertyUtilsBean.getNestedProperty(PropertyUtilsBean.java:808)
    at org.apache.commons.beanutils.PropertyUtils.getNestedProperty(PropertyUtils.java:433)

有人可以提供任何帮助吗?protobuf 生成的类的 getter 方法如下所示:

public java.util.List<com.my.trial.MyTrial.RulePolicyGuid> getTriggersList() {
      return triggers_;
    }

所以这不是问题。我也尝试过使用"header.triggersList(0).ruleGuid",但也没有用。

我的用例是转换用户给定的字符串输入以从 bean 获取所需的属性。所以像java流这样的东西是行不通的。

标签: javaapache-commons-beanutilsprotocol-buffers

解决方案


推荐阅读