简体   繁体   English

为什么即使我要具体导入确切的类,Class.forName也会引发ClassNotFoundException异常?

[英]Why Class.forName thowing a ClassNotFoundException even though I'm specifically importing that exact class?

I have the following code: 我有以下代码:

Class<?> classType = Class.forName(typeClassName);

It keeps throwing an error everytime I try to run the code: 每当我尝试运行代码时,它总是引发错误:

java.lang.ClassNotFoundException: EmailAddress

But I'm speciaifially importing the EmailAddress class into the class that I'm running the first code: 但是我专门将EmailAddress类导入正在运行第一个代码的类中:

import ie.folder.EmailAddress;

How can this be? 怎么会这样?

If you are already importing the class there is no need to use reflection, you can just do 如果您已经导入了该类,则无需使用反射,您可以这样做

Class<EmailAddress> clazz = EmailAddress.class;

You would only really need to use Class.forName if you do not know the class name at the time you compile your program. 如果您在编译程序时不知道类名,则只需要真正使用Class.forName If you still want to do that, you need to use the fully qualified class name (the imports do not matter, they are not considered at runtime, only during compilation). 如果仍要这样做,则需要使用完全限定的类名(导入无关紧要,它们仅在编译时才在运行时考虑)。

Class<?> clazz = Class.forName("ie.folder.EmailAddress");

And you have to deal with the exception if that class could not be found or loaded. 如果找不到或加载该类,则必须处理该异常。

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

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