简体   繁体   中英

Reflection throws Exception. Why?

OK for example I have this code:

class Document {

// blablabla

}

and my main:

Object cl =Class.forName("Document"); // throws ClassNotFoundException: Document

Why it cannot find my class definition?

您应该使用全限定名来引用您的班级:

Object cl =Class.forName("org.yourpackage.Document");

My guess is that the class is actually in a package. Class.forName takes the fully-qualified name, as document:

Parameters:
className - the fully qualified name of the desired class.

For example:

package foo.bar;

class Document {}

...

Class<?> clazz = Class.forName("foo.bar.Document");

If it's a nested class, you need to take that into account too:

package foo.bar;

class Outer {
    static class Document {
    }
}

...

Class<?> clazz = Class.forName("foo.bar.Outer$Document");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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