Search code examples
javafunction-calldynamicobject

dynamic object creation and function call


The problem is to call Honda class display method. Which class method will be called depends upon the string variable that will be passed at runtime. Here I have used one parent class of Honda so that I can achieve runtime polymorphism. But then I am getting ClassNotFoundException even that is included in the throws clause of main. Unable to figure what to do.

Here is the code of all the three classes which are there in the same package.

Vechicle.java

package com.company;

public class Vehicle {
    public void display() {
        System.out.println("Random text");
    }
}

Honda.java

package com.company;

public class Honda extends Vehicle{
    public void display()
    {
        System.out.print("honda called");
    }

}

Main.java

package com.company;

import java.lang.reflect.InvocationTargetException;

public class Main {

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {

            String className = "Honda";
            Class cls = Class.forName(className);
            Vehicle v = (Vehicle) cls.getDeclaredConstructor().newInstance();
            v.display();
    }
}

The error which I am getting is :

Exception in thread "main" java.lang.ClassNotFoundException: Honda
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    at java.base/java.lang.Class.forName0(Native Method)
    at java.base/java.lang.Class.forName(Class.java:315)
    at com.company.Main.main(Main.java:10)

I think I need to handle the ClassNotFoundException in Honda class also but extends and throws can't work simultaneously. Please help me in finding the issue.


Solution

  • But then I am getting ClassNotFoundException even that is included in the throws clause of main.

    A throws clause doesn't stop an exception happening - it just specifies that the method might throw that checked exception.

    The problem is that Class.forName accepts a fully-qualified class name, and you don't have a class with a fully-qualified name of Honda. You have a class with a fully-qualified name of com.company.Honda.

    If you change the start of your code to:

    String className = "com.company.Honda";
    

    ... then I expect that will solve the problem.