简体   繁体   English

Java生成的Protobuf反射,但没有找到类

[英]Java reflection on generated Protobuf but class not found

I've used protobuf a lot. 我经常使用protobuf。 But today, when I tried to use reflection on a generated protobuf class, I got a class not found exception. 但是今天,当我尝试在生成的protobuf类上使用反射时,我得到了一个未找到类的异常。 (I know it's not a normal protobuf usecase). (我知道这不是一个普通的protobuf用例)。 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. 刚刚发现它与protobuf无关。 It's about how to refer an inner class. 这是关于如何引用内部类。

All generated protobuf classes are static inner classes. 所有生成的protobuf类都是静态内部类。 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"). 表示完全限定类名的最后一部分:Class.forName(“com.foo.protobuf.Foo $ Bar”)。

Sorry for answering my own question. 很抱歉回答我自己的问题。 Hope it helps someone who is in the same situation. 希望它可以帮助处于相同情况的人。

Everything is perfect. 一切都很完美。

possibility of issue. 问题的可能性。

Your classpath is broken (which is a very common problem in the Java world). 你的类路径被破坏了(这是Java世界中一个非常普遍的问题)。

If you know the path of the class or the jar containing the class then add it to your classpath while running it. 如果您知道类的路径或包含该类的jar,则在运行它时将其添加到类路径中。 You can use the classpath as mentioned here: 您可以使用此处提到的类路径:

on Windows 在Windows上

java -classpath .;yourjar.jar YourMainClass
on UNIX/Linux

java -classpath .:yourjar.jar YourMainClass

in your case answer is 在你的情况下答案是

All generated protobuf classes are static inner classes. 所有生成的protobuf类都是静态内部类。 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"). 表示完全限定类名的最后一部分:Class.forName(“com.foo.protobuf.Foo $ Bar”)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM