I've seen a post regarding whether or not Class.forName can return null here and everyone seems to think it can't (or wont). However, it is returning null for me with this code:
public void init() {
File binDriectory = new File("./bin/dft");
String[] files = binDriectory.list();
for (String file : files) {
if (file.endsWith(".class")) {
if (file.indexOf("DataReader") > 0) {
//strip off the ".class"
String className = file.substring(0, file.indexOf(".class"));
try {
//load the class
Class readerclass = Class.forName("dft." + className);
//get the file extension of the file type this class deals with
/* NullPointerException thrown here in call to getMthod() */
Method getExtensionMethod = readerClass.getMethod("getFileExtension", null);
String extension = (String) getExtensionMethod.invoke(readerClass.newInstance(), null);
//add the extension and class to the class map
classMap.put(extension, readerClass);
//add the extension to the list of reader file extensions
readerExtensions.add(extension);
}
catch (ClassNotFoundException e) {
System.err.println("**WARNING: class not found: dft." + className);
continue;
}
catch (NoSuchMethodException e) {
System.err.println("**WARNING: class dft." + className + " does "
+ "not contain a getFileExtension() method.");
continue;
}
catch (InstantiationException e) {
System.err.println("**WARNING: could not create an instance of "
+ "class dft." + className);
continue;
}
/* with Java 7, these next two catch blocks can be combined (and they
should) */
catch (InvocationTargetException e) {
System.err.println("**WARNING: could not invoke getFileExtension()"
+ " method from class dft." + className);
continue;
}
catch (IllegalAccessException e) {
System.err.println("**WARNING: could not invoke getFileExtension()"
+ " method from class dft." + className);
continue;
}
System.out.println(className);
}
else if (file.indexOf("DataWriter") > 0) {
System.out.println(file);
}
}
}
}
ClassNotFoundException is NOT thrown, but the result of forName() is null. The documentation says nothing about returning null.
Does anyone have any clue as to why this is happening? I tested the call of forName() in another project that doesn't use a package name (the code above is in a package named "dft"), and that one worked fine. I'm thinking that has something to do with it. The classpath is fine as well--the .class files are in ...bin/dft and the classpath contains .../bin. I even tried adding the .../bin/dft directory explicitly in the classpath just in case, and it still returns null.
You are assigning the value returned by forName
to
readerclass
(lowercase C)
but calling getMethod
from
readerClass
(uppercase C)
which probably is an uninitialized field.
Java is case-sensitive.