0

While creating an object of using Class.forName() I am getting following Errors. Can you please confirm where I am doing wrong.

Exception in thread "main" java.lang.ClassNotFoundException: ABC
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
    at RandomPrograms.ClassObjectFromString.main(ClassObjectFromString.java:32)

ClassObjectFromString.java

import java.lang.reflect.Constructor;

class ABC {
    ABC() {
        System.out.println("ABC called!!! ");
    }
    ABC(String a) {
        System.out.println("ABC called : " + a);
    }
}

class ClassObjectFromString {

    public static void main(String[] args) throws Exception {
        Class<?> clazz = Class.forName("ABC");
        Constructor<?> ctor = clazz.getConstructor(String.class);
        Object object = ctor.newInstance(new Object[] { "Message" });
    }
}

2 Answers 2

3
public static Class<?> forName(String className)

Provide the fully qualified name of the desired class which includes your package name too. So it will we RandomPrograms.ABC

Sign up to request clarification or add additional context in comments.

Comments

0

There are a few things wrong here:

  1. You need to use the fully qualified class name in the form 'packageName.className'.
  2. Your constructors need to be declared public for reflection to work.

So your code should look like (assuming package name is RandomPrograms, replace with yours as needed):

public class ClassObjectFromString {

    public static void main(String[] args) throws Exception {
        Class<?> clazz = Class.forName("RandomPrograms.ABC");
        Constructor<?> ctor = clazz.getConstructor(String.class);
        Object object = ctor.newInstance(new Object[] { "Message" });
    }

}

class ABC {
    public ABC() {
        System.out.println("ABC called!!! ");
    }
    public ABC(String a) {
        System.out.println("ABC called : " + a);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.