Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Class.forName failing

I cannot seem to get Class.forName(String) to not throw a ClassNotFoundException. For example, this code which is a shortened copy of code directly from Sun's website throws the exception.

import java.lang.reflect.*;
class A {}

public class Test {
   public static void main(String args[])
   {
      try {
         Class cls = Class.forName("A");
      }
      catch (Throwable e) {
         System.err.println(e);
      }
   }
}

Produces

java.lang.ClassNotFoundException: A

I am using Eclipse 1.3.2.20110218-0812 on Windows XP SP3. Does anyone know what I am missing?

like image 597
user727125 Avatar asked Apr 27 '11 11:04

user727125


People also ask

What is Java class forName?

class.forName() is a method in Java that returns the class object associated with the class or interface passed as the first parameter (i.e., name). This method is declared in the following way:​ ClassLoaders are responsible for loading classes into the memory.

Why do we write class forName () in JDBC?

Use the Class. forName() method to load the driver. The forName() method dynamically loads a Java class at runtime. When an application calls the forName() method, the Java Virtual Machine (JVM) attempts to find the compiled form (the bytecode) that implements the requested class.

Which type of exception will be thrown by forName () method?

ClassNotFoundException: if the class cannot be located.


3 Answers

You have to prepend the package name of the Test class to A, as an example if Test were in "test" package, you'd need following:

Class cls = Class.forName("test.A");
like image 92
Tomasz Stanczak Avatar answered Sep 27 '22 21:09

Tomasz Stanczak


Your snippet works fine for me.

Here is a demo at ideone.com: http://ideone.com/IBjKl

Note that you need to provide the fully qualified name of the class for the class loader to find it. I.e., if A is actually in some package, you need to do forName("your.package.A") for it to work.

(Note that the import is unnecessary.)

like image 44
aioobe Avatar answered Sep 27 '22 21:09

aioobe


Class.forName function needs the fully specified class path. So even if you have imported ArrayList from java.util you should use:

Class myClass = Class.forName("java.util.ArrayList");

that is your problem.

like image 31
omerkirk Avatar answered Sep 27 '22 21:09

omerkirk