Java反射学习笔记

Java反射

1.方法

//根据类名返回类的对象

Class classBook = Class.forName("com.android.peter.reflectdemo.Book");

//创建实例

Object objectBook = classBook.newInstance();

//转换

Book book = (Book) objectBook;

......

Class classBook = Class.forName("com.android.peter.reflectdemo.Book");

//反射私有的构造方法

Constructor declaredConstructorBook = classBook.getDeclaredConstructor(String.class,String.class);

//取消权限控制检查

declaredConstructorBook.setAccessible(true);

//创建实例

Object objectBook = declaredConstructorBook.newInstance("Android开发艺术探索","任玉刚");

//转换

Book book = (Book) objectBook;

......

Class classBook = Class.forName("com.android.peter.reflectdemo.Book");
Object objectBook = classBook.newInstance();

//反射私有属性

Field fieldTag = classBook.getDeclaredField("TAG");

//取消权限控制检查

fieldTag.setAccessible(true);

//获取该实例的私有属性

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);

你可能感兴趣的:(Java反射学习笔记)