webish webish - 1 year ago 132
Java Question

Java Class.forName method java.lang.ClassNotFoundException;

I've found other thread where people had and solved this error; however, all of were NOT using fully qualified class paths. I cannot seem to get Class.forName to work and I am using fully qualified paths.

I've tested compiling from CLI and using ItelliJ Idea. Both fail with the same error.

Code (in test directory):

package test;
public class Test {
public static void main(String[] args) {
Class cls = Class.forName("java.util.ArrayList");


java.lang.ClassNotFoundException; must be caught or declared to be thrown

The example above does NOT work. Thanks in advance!

Answer Source

You're getting this message because ClassNotFoundException is a checked exception. This means that this exception can not be ignored. You need to either surround it with a try/catch construct and provide exception handling or add a throws clause to your method and handle it in a callee.

EDIT: Please note that Class.forName() construct is not resolved during compilation. When you write such a statement, you're telling the JVM to look during program execution for a class which may not have been loaded. Java libraries are dynamically linked instead of statically linked, meaning that their code is not incorporated in your program code, being loaded only when requested. This is why it throws ClassNotFoundException.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download