gpt4 book ai didi

java - 反射方法时抛出 TypeNotPresentException

转载 作者:行者123 更新时间:2023-11-30 11:08:53 31 4
gpt4 key购买 nike

我有一个子类,它有一个在 Android 项目中抛出异常的方法。

public class Bar extends Foo {
public void method(String someClass) throws ReflectiveOperationException {
Class.forName(someClass);
}
}

我有一个基类,它的方法反射(reflect)了它自己的方法,当然可以从子类中调用这些方法。

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 上运行代码,但 ReflectiveOperationExceptionClassNotFoundExceptionIllegalAccessException 的基类、InstantiationExceptionInvocationTargetExceptionNoSuchFieldExceptionNoSuchMethodException 自 API 19 以来。

如果您希望与低于 19 的 API 级别兼容,请不要在 throws 子句中使用 ReflectiveOperationException

public class Bar extends Foo {
public void method(String someClass) throws ClassNotFoundException {
Class.forName(someClass);
}
}

关于java - 反射方法时抛出 TypeNotPresentException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28355206/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com