反射方法时抛出 TypeNotPresentException
TypeNotPresentException thrown when reflecting on a method
我有一个子 class,它有一个在 Android 项目中抛出异常的方法。
public class Bar extends Foo {
public void method(String someClass) throws ReflectiveOperationException {
Class.forName(someClass);
}
}
我有一个基础 class,它的方法反映了它自己的方法,当然,可以从子class.
调用
public class Foo {
public void reflectOnMethods() {
for (Method m : this.getClass().getDeclaredMethods()) {
//do stuff with methods
}
}
}
当 Bar 调用其继承的 reflectOnMethods 时,我看到了这样的堆栈跟踪
02-05 21:58:04.461: E/AndroidRuntime(2737): java.lang.TypeNotPresentException: Type java/lang/ReflectiveOperationException not present
02-05 21:58:04.461: E/AndroidRuntime(2737): at java.lang.Class.getDeclaredMethods(Native Method)
02-05 21:58:04.461: E/AndroidRuntime(2737): at java.lang.Class.getDeclaredMethods(Class.java:703)
当我将抛出的异常从 ReflectiveOperationException
更改为 ClassNotFoundException
时,问题消失了,但是 为什么要这样解决??!!?
我对此感到困惑,并会查看 JDK 来源以尝试找出答案,但我觉得很懒惰。
问题是您正在尝试 运行 API <19 上的代码,但是 ReflectiveOperationException
是 ClassNotFoundException
的基础 class, IllegalAccessException
、InstantiationException
、InvocationTargetException
、NoSuchFieldException
和 NoSuchMethodException
自 API 19.
如果您希望与低于 19 的 API 级别兼容,请不要在 throws 子句中使用 ReflectiveOperationException
。
public class Bar extends Foo {
public void method(String someClass) throws ClassNotFoundException {
Class.forName(someClass);
}
}
我有一个子 class,它有一个在 Android 项目中抛出异常的方法。
public class Bar extends Foo {
public void method(String someClass) throws ReflectiveOperationException {
Class.forName(someClass);
}
}
我有一个基础 class,它的方法反映了它自己的方法,当然,可以从子class.
调用public class Foo {
public void reflectOnMethods() {
for (Method m : this.getClass().getDeclaredMethods()) {
//do stuff with methods
}
}
}
当 Bar 调用其继承的 reflectOnMethods 时,我看到了这样的堆栈跟踪
02-05 21:58:04.461: E/AndroidRuntime(2737): java.lang.TypeNotPresentException: Type java/lang/ReflectiveOperationException not present
02-05 21:58:04.461: E/AndroidRuntime(2737): at java.lang.Class.getDeclaredMethods(Native Method)
02-05 21:58:04.461: E/AndroidRuntime(2737): at java.lang.Class.getDeclaredMethods(Class.java:703)
当我将抛出的异常从 ReflectiveOperationException
更改为 ClassNotFoundException
时,问题消失了,但是 为什么要这样解决??!!?
我对此感到困惑,并会查看 JDK 来源以尝试找出答案,但我觉得很懒惰。
问题是您正在尝试 运行 API <19 上的代码,但是 ReflectiveOperationException
是 ClassNotFoundException
的基础 class, IllegalAccessException
、InstantiationException
、InvocationTargetException
、NoSuchFieldException
和 NoSuchMethodException
自 API 19.
如果您希望与低于 19 的 API 级别兼容,请不要在 throws 子句中使用 ReflectiveOperationException
。
public class Bar extends Foo {
public void method(String someClass) throws ClassNotFoundException {
Class.forName(someClass);
}
}