Ernusc
Ernusc

Reputation: 526

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?

Upvotes: 0

Views: 103

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1499830

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");

Upvotes: 2

Mureinik
Mureinik

Reputation: 311063

you should refer to your class with it's fully qualified name:

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

Upvotes: 5

Related Questions