ServerServiceDefinition与自定义类的关系及从Server获取其成员变量的疑问
Let's break down your two questions one by one:
1. Why can MetadataStoreImpl be passed to addService?
Looking at the method signature you shared:
public abstract T addService(ServerServiceDefinition service);
This is just one of the overloaded versions of addService provided by ServerBuilder. There's another commonly used overload that accepts a BindableService instance:
public T addService(BindableService bindableService)
Your MetadataStoreImpl class is almost certainly extending the abstract service base class generated by the gRPC compiler (something like MetadataStoreGrpc.MetadataStoreImplBase). That abstract base class implements the BindableService interface, which has a bindService() method that generates the required ServerServiceDefinition under the hood.
When you pass new MetadataStoreImpl(...) to addService, the method automatically calls bindService() on your instance to convert it into the ServerServiceDefinition the builder needs. That's why your code works without explicit conversion.
2. How to get a reference to MetadataStoreImpl's member variables from the server instance?
The gRPC Server class doesn't expose direct access to the service instances you added to it—its focus is on managing the server lifecycle, not holding onto service references for you.
The cleanest and most recommended approach is to hold onto the MetadataStoreImpl instance yourself before passing it to the builder:
// Create and store the service instance first MetadataStoreImpl metadataService = new MetadataStoreImpl(this.config, port); // Then pass it to the server builder server = ServerBuilder.forPort(port) .addService(metadataService) .executor(Executors.newFixedThreadPool(numThreads)) .build() .start(); // Now you can access its member variables directly whenever you need SomeType value = metadataService.getYourMemberVariable();
If for some reason you can't pre-store the instance (not recommended), you could use reflection to dig into the server's internal state, but this is fragile—gRPC's internal implementation might change in future versions, breaking your code. So sticking with the explicit reference is the way to go.
内容的提问来源于stack exchange,提问作者Feihua Fang

