简体   繁体   中英

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.

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();
    }
}

将完整的程序包名称传递给forName方法。

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

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