I've used protobuf a lot. But today, when I tried to use reflection on a generated protobuf class, I got a class not found exception. (I know it's not a normal protobuf usecase). The class was being used in the same file by other methods, and it's compiled and ran without problems.
import com.foo.protobuf.Foo.Bar;
...
void method1() {
Bar.Builder bld = Bar.newBuilder();
...
}
void method2(String clsName) {
// clsName = "com.foo.protobuf.Foo.Bar"
Class clsBar = Class.forName(clsName); // CNF Exception here
}
What's wrong with my code? Thanks for any input.
Just found out it has nothing to do with protobuf. It's about how to refer an inner class.
All generated protobuf classes are static inner classes. In order to make it work, I have to use '$' instead of '.' to denote the last part of the fully qualified classname: Class.forName("com.foo.protobuf.Foo$Bar").
Sorry for answering my own question. Hope it helps someone who is in the same situation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With