Java反射
1.方法
//根據(jù)類名返回類的對(duì)象
Class<?> classBook = Class.forName("com.android.peter.reflectdemo.Book");
//創(chuàng)建實(shí)例
Object objectBook = classBook.newInstance();
//轉(zhuǎn)換
Book book = (Book) objectBook;
......
Class<?> classBook = Class.forName("com.android.peter.reflectdemo.Book");
//反射私有的構(gòu)造方法
Constructor<?> declaredConstructorBook = classBook.getDeclaredConstructor(String.class,String.class);
//取消權(quán)限控制檢查
declaredConstructorBook.setAccessible(true);
//創(chuàng)建實(shí)例
Object objectBook = declaredConstructorBook.newInstance("Android開(kāi)發(fā)藝術(shù)探索","任玉剛");
//轉(zhuǎn)換
Book book = (Book) objectBook;
......
Class<?> classBook = Class.forName("com.android.peter.reflectdemo.Book");
Object objectBook = classBook.newInstance();
//反射私有屬性
Field fieldTag = classBook.getDeclaredField("TAG");
//取消權(quán)限控制檢查
fieldTag.setAccessible(true);
//獲取該實(shí)例的私有屬性
String tag = (String) fieldTag.get(objectBook);
......
Class<?> cServiceManager = Class.forName("android.os.ServiceManager");
//反射方法
Method mGetService = cServiceManager.getMethod("getService", String.class);
Object oNotificationManagerService = mGetService.invoke(null, Context.NOTIFICATION_SERVICE);
Class<?> cINotificationManagerStub = Class.forName("android.app.INotificationManager$Stub");
Method mAsInterface = cINotificationManagerStub.getMethod("asInterface",IBinder.class);
Object oINotificationManager = mAsInterface.invoke(null,oNotificationManagerService);
Method mGetZenMode = cINotificationManagerStub.getMethod("getZenMode");
zenMode = (int) mGetZenMode.invoke(oINotificationManager);