我在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");
结果:
变量unusedVar
不是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
是接口而不是类吗?
答案 0 :(得分:1)
接口OnSystemUiVisibilityChangeListener
嵌套在课程View
中,所以我相信您必须Class.forName("android.view.View$OnSystemUiVisibilityChangeListener");
(请注意'$')。
参考文献: