简体   繁体   中英

How to make sure a String matches a Java class name

Using reflection and the Class.forName(String s) method, is there a way to determine if my String matches the proper case of the class?

example:

Class: testReflection.java
String s: testReFlEction

try{   
    Class.forName(s)
}
    catch(ClassNotFoundException e){
    System.out.println("Can't find class: " + s);
}

This misses the ClassNotFoundException and throws this exception: Exception in thread "main" java.lang.NoClassDefFoundError: testReFlEction (wrong name: testReflection)

Error Log:

Exception in thread "main" java.lang.NoClassDefFoundError: ReFlEction (wrong name:  testReflection)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at Reflection.findClass(testReflection.java:50)
at Reflection.main(testReflection.java:75)

Update: I changed the exception to catch Throwable .

我通过将要捕获的异常类型从ClassNotFoundException更改为Throwable解决了我的问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM