如何在JavaScript中获取Protobuf消息类型的全限定路径?
获取JavaScript Protobuf消息的全限定名
当然可以实现!在官方protoc编译生成的JavaScript Protobuf代码中,每个消息类都自带了包含元数据的descriptor静态属性,其中的full_name字段正是你需要的全限定路径字符串,和C++里GetDescriptor()->full_name()的效果完全一致。
具体实现方法
有两种方式可以获取:
直接通过消息类获取
你可以直接访问导出的消息类的静态descriptor属性,读取full_name:import { Status } from 'gen/my/messages/proto/status_pb.js'; const fullQualifiedName = Status.descriptor.full_name; console.log(fullQualifiedName); // 输出: "my.messages.proto.Status"通过消息实例获取
如果已经创建了消息实例,也可以通过实例的constructor属性拿到对应的类,再访问descriptor:import { Status } from 'gen/my/messages/proto/status_pb.js'; const status = new Status(); const instanceFullName = status.constructor.descriptor.full_name; console.log(instanceFullName); // 同样输出: "my.messages.proto.Status"
为什么控制台输出能看到这个名字?
你在console.log(status)时看到的my.messages.proto.Status前缀,其实是Protobuf JS生成的类的toString()方法自动使用了descriptor.full_name的值,所以这个元数据一直都存在,只是需要通过descriptor属性来直接访问。
这个descriptor对象里还包含了很多其他元信息,比如消息的字段定义、包名等,如果你有其他元数据相关的需求,也可以从这里获取。
内容的提问来源于stack exchange,提问作者sma
相关产品推荐
相关产品推荐

