Android 通过反射机制获取StorageVolume中的 getPathFile()方法

        通过反射机制获取StorageVolume中的getPathFile()方法。
        首先定义了一个静态方法 getPathFile(),接受一个 StorageVolume 对象作为参数,并返回一个 File 对象。在方法内部,通过 Class.forName() 方法获取 android.os.storage.StorageVolume 类的 Class 对象。使用 getDeclaredMethod() 方法获取 getPathFile() 方法的 Method 对象。调用 setAccessible(true) 方法,使得私有方法可访问。
        使用 invoke() 方法调用 getPathFile() 方法,并将结果强制转换为 File 类型。如果在上述步骤中捕获到了异常(ClassNotFoundException、NoSuchMethodException、IllegalAccessException、InvocationTargetException),则打印异常堆栈轨迹。如果没有捕获到异常,则返回反射调用后得到的 pathFile 对象。如果发生异常,则返回 null。

/**
 * 反射机制调用 getPathFile
 */
public static File getPathFile(StorageVolume storageVolume) {
    try {
        // 获取StorageVolume类
        Class<?> storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
        // 获取getPathFile()方法
        Method getPathFileMethod = storageVolumeClazz.getDeclaredMethod("getPathFile");
        getPathFileMethod.setAccessible(true);
        // 调用getPathFile()方法
        File pathFile = (File) getPathFileMethod.invoke(storageVolume);
        Log.d(TAG, "getPathFile: 反射机制调用 getPathFile = " + pathFile);
        return pathFile;
    } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
        e.printStackTrace();
    }
    return null;
}

   StorageVolume 中的getPathFile()方法。

/** {@hide} */
    public File getPathFile() {
        return mPath;
    }

   StorageVolume 类中的 getPathFile() 方法是在 Android 10(API 级别 29)中被隐藏的。从 Android 10 开始,该方法不再公开可用,并且在 SDK 中无法直接访问。

  • 12
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值