我在一个 Android 项目中使用 Java 反射。
源代码:
Log.d("LOG", "begin");
try {
final android.view.View.OnSystemUiVisibilityChangeListener unusedVar = new android.view.View.OnSystemUiVisibilityChangeListener() {
@Override
public void onSystemUiVisibilityChange(int visibility) {
// TODO Auto-generated method stub
}
};
Log.d("LOG", "unusedVar is null = " + (unusedVar == null? "Yes": "No"));
Class newClass = Class.forName("android.view.View.OnSystemUiVisibilityChangeListener");
Log.d("LOG", "newClass created");
} catch (Exception ex) {
Log.d("LOG", "Failed to create newClass", ex);
}
Log.d("LOG", "end");
- 上面的代码在我活动的 onCreate() 中。
- 该项目的构建目标是 Android 4.0。
- 我在装有 Android 4.0.4 的设备上运行它。
结果:
变量unusedVar
为 NOT null
,但Class.forName
抛出ClassNotFoundException
.
日志:
D/LOG(13205): begin
D/LOG(13205): unusedVar is null = No
D/LOG(13205): Failed to create newClass
D/LOG(13205): java.lang.ClassNotFoundException: android.view.View.OnSystemUiVisibilityChangeListener
D/LOG(13205): at java.lang.Class.classForName(Native Method)
D/LOG(13205): at java.lang.Class.forName(Class.java:217)
D/LOG(13205): at java.lang.Class.forName(Class.java:172)
D/LOG(13205): at com.MyActivity.onCreate(VideoPlayerActivity.java:100)
D/LOG(13205): at android.app.Activity.performCreate(Activity.java:4465)
D/LOG(13205): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
D/LOG(13205): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
D/LOG(13205): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
D/LOG(13205): at android.app.ActivityThread.access$600(ActivityThread.java:123)
D/LOG(13205): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
D/LOG(13205): at android.os.Handler.dispatchMessage(Handler.java:99)
D/LOG(13205): at android.os.Looper.loop(Looper.java:137)
D/LOG(13205): at android.app.ActivityThread.main(ActivityThread.java:4424)
D/LOG(13205): at java.lang.reflect.Method.invokeNative(Native Method)
D/LOG(13205): at java.lang.reflect.Method.invoke(Method.java:511)
D/LOG(13205): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
D/LOG(13205): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
D/LOG(13205): at dalvik.system.NativeStart.main(Native Method)
D/LOG(13205): Caused by: java.lang.NoClassDefFoundError: android/view/View/OnSystemUiVisibilityChangeListener
D/LOG(13205): ... 18 more
D/LOG(13205): Caused by: java.lang.ClassNotFoundException: android.view.View.OnSystemUiVisibilityChangeListener
D/LOG(13205): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
D/LOG(13205): at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
D/LOG(13205): at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
D/LOG(13205): ... 18 more
D/LOG(13205): end
这是为什么?是因为android.view.View.OnSystemUiVisibilityChangeListener
是接口而不是类吗?