-1

following is the code, when i am giving command java Test A then i am getting error NoClassDefFoundError and when i give command java Test S then error is ClassNotFound.

As per my knowledge if newInstance() is used and class is not found then ClassNotFound error should com

Why is there difference in the errors?

enter image description here

class Test {

public static void main(String[] args) throws Exception
{
    System.out.println("In Main Method");
    Object o = Class.forName(args[0]).newInstance();
    System.out.println(o.getClass().getName());
}

}

class Student
{

}

class Teacher
{

}
  • 1
    What is it you think the "A" is doing in your command... – slambeth Aug 23 '17 at 16:03
  • @slambeth A or Student or S is the class name for which object has to be created – springcloudlearner Aug 23 '17 at 16:06
  • ...yes, but you'll need that class to actually exist in your classpath to load it and create an instance of it. As an experiment, try your command with "java.lang.String" in place of the "A". – slambeth Aug 23 '17 at 19:49
  • @slambeth correct and if class is not found then classnotfoundexception will be thrown. My question is in case I am passing A as class then I am getting noclassdeffounderror - why is it so? – springcloudlearner Aug 23 '17 at 19:52
  • Not sure what you did, but ClassNotFoundException is all that is going to happen with Class.forName(); – slambeth Aug 23 '17 at 19:56

1 Answers1

-1

As per my knowledge if newInstance() is used and class is not found then ClassNotFound error should com

    @CallerSensitive
public static Class<?> forName(String className)
            throws ClassNotFoundException {
    Class<?> caller = Reflection.getCallerClass();
    return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
}

forName method is throwing the ClassNotFoundException exception.

newInstance method is throwing InstantiationException and IllegalAccessException

I'm not able to reproduce your issue, in each case I get a ClassNotFoundException

luk2302
  • 55,258
  • 23
  • 97
  • 137
Thomas.L
  • 321
  • 1
  • 6