lee tan
lee tan

Reputation: 133

Can't instantiate a class through reflection

When I user java reflection to create object,It will throw an "java.lang.ClassNotFoundException",this is my code:

public class Demo {
    public static void main(String[] args) throws Exception {
        Class clazz = Class.forName("Demo");
        Demo d = (Demo) clazz.newInstance();
    }
}

where I was wrong.

Upvotes: 0

Views: 349

Answers (3)

Chris Mowforth
Chris Mowforth

Reputation: 6723

Or, bonus points for a java.lang.invoke based solution :)

    MethodType mt; MethodHandle mh;
    MethodHandles.Lookup lookup = MethodHandles.lookup();

    mt = MethodType.methodType(void.class);

    try {
        Class klass = Class.forName("com.mycompany.mypackage.Demo");
        mh = lookup.findConstructor(klass, mt);

        Object obj = (Object)mh.invoke();
    } catch (Throwable ex) {
        // ERR
        System.out.println(ex);
    }

Upvotes: 0

Peeyush
Peeyush

Reputation: 432

Pass complete package name to forName method .

Upvotes: 1

Bohemian
Bohemian

Reputation: 424983

You must use the fully qualified name of the class, ie including the package, eg:

public class Demo {
    public static void main(String[] args) throws Exception {
        Class clazz = Class.forName("com.mycompany.mypackage.Demo");
        Demo d = (Demo) clazz.newInstance();
    }
}

Upvotes: 10

Related Questions