使用reflection
和Class.forName(String s)
方法,有没有办法确定我的字符串是否符合该类的正确情况?
示例:
Class: testReflection.java
String s: testReFlEction
try{
Class.forName(s)
}
catch(ClassNotFoundException e){
System.out.println("Can't find class: " + s);
}
这会错过ClassNotFoundException并抛出此异常:线程“main”中的异常java.lang.NoClassDefFoundError:testReFlEction(错误名称:testReflection)
错误日志:
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)
更新:
我更改了异常以捕获Throwable
。
答案 0 :(得分:0)
我通过将我从ClassNotFoundException
抓取的异常类型更改为Throwable
来解决了我的问题。