使用反射从 Bundle 中获取数据
Get data from a Bundle using reflection
我正在尝试读取传入包中存储的数据,但我不知道要获取的密钥。
我正在使用反射在 运行 时间从包中读取方法和字段,这样我就能够掌握包含键和值的集合,然后我就能够迭代它们。
因此,一旦我掌握了捆绑包,我就会使用反射:
Class<?> bundleClass = bundle.getClass();
现在,值存储在 superclass (BaseBundle) 中的 ArrayMap 中,所以我调用它来获取 superclass:
Class<?> superClass = bundleClass.getSuperclass();
但是遍历 superClass.getDeclaredMethods(); returns 只有对象类型的方法,这意味着我需要将它转换为 BaseBundle。
我无法将其转换为 class BaseBundle - 我尝试使用 superClass.cast 和显式转换,但编译器抱怨。
将 superclass 对象转换为其类型 (BaseBundle) 的最佳方法是什么。
另外,我说的对吗,使用反射我将能够读取存储在包中的值?
更新:
我的最终目标是以某种方式找到包中存储 URL 或其他一些图像引用的位置。由于我不知道捆绑包是如何构建的,因此我需要以某种方式调查捆绑包。
任何关于如何找到该图像参考的建议将不胜感激
假设您正在谈论 android.os.Bundle
: you don’t have to use reflection. BaseBundle
provides the method keySet()
returns 此捆绑包中使用的所有密钥的列表。
示例:
Bundle bundle = getMyBundle();
for (String key : bundle.keySet()) {
String value = bundle.get(key);
try {
URL url = new URL(value);
// no exception thrown! this is a valid URL
// do something with ulr
} catch (MalformedURLException exception) {
// this item is no URL
}
}
我正在尝试读取传入包中存储的数据,但我不知道要获取的密钥。
我正在使用反射在 运行 时间从包中读取方法和字段,这样我就能够掌握包含键和值的集合,然后我就能够迭代它们。
因此,一旦我掌握了捆绑包,我就会使用反射:
Class<?> bundleClass = bundle.getClass();
现在,值存储在 superclass (BaseBundle) 中的 ArrayMap 中,所以我调用它来获取 superclass:
Class<?> superClass = bundleClass.getSuperclass();
但是遍历 superClass.getDeclaredMethods(); returns 只有对象类型的方法,这意味着我需要将它转换为 BaseBundle。
我无法将其转换为 class BaseBundle - 我尝试使用 superClass.cast 和显式转换,但编译器抱怨。
将 superclass 对象转换为其类型 (BaseBundle) 的最佳方法是什么。 另外,我说的对吗,使用反射我将能够读取存储在包中的值?
更新:
我的最终目标是以某种方式找到包中存储 URL 或其他一些图像引用的位置。由于我不知道捆绑包是如何构建的,因此我需要以某种方式调查捆绑包。
任何关于如何找到该图像参考的建议将不胜感激
假设您正在谈论 android.os.Bundle
: you don’t have to use reflection. BaseBundle
provides the method keySet()
returns 此捆绑包中使用的所有密钥的列表。
示例:
Bundle bundle = getMyBundle();
for (String key : bundle.keySet()) {
String value = bundle.get(key);
try {
URL url = new URL(value);
// no exception thrown! this is a valid URL
// do something with ulr
} catch (MalformedURLException exception) {
// this item is no URL
}
}