当一个类中的属性是private的时候,需要将
fieldName.setAccessible(true);
当一个类的属性是静态属性的时候,则直接
itemListField.set(null, arrayList);
参考例子:
// 获取类
Class mediaItemClazz = Class.forName("io.rong.imkit.plugin.image.PictureSelectorActivity$MediaItem");
// 获取属性 Field uriField = mediaItemClazz.getDeclaredField("uri");
// 设置访问权限 uriField.setAccessible(true); Field mediaTypeField = mediaItemClazz.getDeclaredField("mediaType"); mediaTypeField.setAccessible(true);
// 实例化对象 Object item = mediaItemClazz.newInstance();
// 设置属性 uriField.set(item, this.mTakePictureUri.getPath()); mediaTypeField.set(item, 1); Class holderClazz = Class.forName("io.rong.imkit.plugin.image.PictureSelectorActivity$PicItemHolder");
// 获取静态属性 Field itemListField = holderClazz.getDeclaredField("itemList"); itemListField.setAccessible(true); Field itemSelectedListField = holderClazz.getDeclaredField("itemSelectedList"); itemSelectedListField.setAccessible(true); ArrayList arrayList = new ArrayList(); arrayList.add(item);
// 给静态属性赋值 itemListField.set(null, arrayList); itemSelectedListField.set(null, null);