當一個類中的屬性是private的時候,須要將this
fieldName.setAccessible(true);
當一個類的屬性是靜態屬性的時候,則直接spa
itemListField.set(null, arrayList);
參考例子:code
// 獲取類
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);