为什么 Class.forName() 对我不起作用?
我正在尝试从变量实例化一个类,并编写了一些测试代码。 但不幸的是,它不起作用。 代码如下:
Object co1 = new CommandDownloadHttp();
Class cc1 = Class.forName("CommandDownloadHttp");
Object co = cc1.newInstance();
不幸的是,在第二行,它因 java.lang.ClassNotFoundException
崩溃。
你能告诉我我做错了什么吗?
I'm trying to instantiate a class from variable, and wrote some test code. But, unfortunately, it isn't working. Here is the code:
Object co1 = new CommandDownloadHttp();
Class cc1 = Class.forName("CommandDownloadHttp");
Object co = cc1.newInstance();
Unfortunately on second line it crashes with java.lang.ClassNotFoundException
.
Can you please tell me what I am doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
CommandDownloadHttp 是类的完整 名称,即它没有包吗? 如果它确实有一个包,请包括:(
我认为您在实际代码中这样做有更好的理由,顺便说一句 - 显然在这种情况下您实际上不需要通过反射 :)
Is CommandDownloadHttp the full name of the class, i.e. it doesn't have a package? If it does have a package, include that:
(I assume there's a better reason for you doing this in your real code, btw - clearly in this case you don't actually need to fetch the class by reflection :)
你的课程是在一个包中吗? 而且这个包是导入的? 所以它在第 1 行有效。但是您需要 Class.forName("my.package.to.CommandDownloadHttp") 中的完整限定名称。
Is your class in a package? And this package is imported? So it works in line 1. But you need the full qualified name in Class.forName("my.package.to.CommandDownloadHttp").