为什么 Class.forName() 对我不起作用?

发布于 2024-07-13 11:20:25 字数 298 浏览 5 评论 0原文

我正在尝试从变量实例化一个类,并编写了一些测试代码。 但不幸的是,它不起作用。 代码如下:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

兮颜 2024-07-20 11:20:25

CommandDownloadHttp 是类的完整 名称,即它没有包吗? 如果它确实有一个包,请包括:(

Class.forName("foo.bar.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:

Class.forName("foo.bar.CommandDownloadHttp");

(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 :)

孤独难免 2024-07-20 11:20:25

你的课程是在一个包中吗? 而且这个包是导入的? 所以它在第 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").

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文