Set 不能转换为像列表这样的 Set 对象。因此,如果您有一个可以接受任何对象的方法,例如:
public void handler(Object any_var_including_a_set)
有没有办法在不知道集合保存的数据类型的情况下动态迭代集合的内容?
Object.getClass()
Apex 中没有 的概念;另一种方法是使用instanceof
一组已知的类型。
下面的修改handler
使用JSON.serialize
,然后确定ofAnyType
是数组、对象还是其他一些原语。
假设一个数组(aSet
或List
在 Apex 中),它可以转换为List<Object>
. 这可以迭代以确定instanceof
每个成员的 。
另一种实现将使用ofAnyType instanceof Set<Object_Type_Here>
,但并不抽象。
public static void handler(Object ofAnyType)
{
String jsonString = JSON.serialize(ofAnyType);
System.debug(jsonString);
// if array, use List<Object>
if(jsonString.length() > 0 && jsonString.startsWith('[') && jsonString.endsWith(']'))
{
List<Object> mapped = (List<Object>)JSON.deserializeUntyped(jsonString);
// iterate over mapped, check type of each Object o within iteration
for(Object o : mapped)
{
if(o instanceof String)
{
System.debug((String)o);
}
}
}
// if object, use Map<String, Object>
else if(jsonString.length() > 0 && jsonString.startsWith('{') && jsonString.endsWith('}'))
{
Map<String, Object> mapped = (Map<String,Object>)JSON.deserializeUntyped(jsonString);
// iterate over mapped, check type of each Object o within iteration
for(Object o : mapped.values())
{
if(o instanceof String)
{
System.debug((String)o);
}
}
}
}
为了快速测试,我保存handler
在我的StackTesting
班级中。您可以使用下面的代码来执行匿名 Apex 并查看结果。
Integer i = 42;
Set<String> strs = new Set<String>{'hello', 'world'};
Set<Object> objs = new Set<Object>{'hello', 2, new Account(Name = 'Sure')};
StackTesting.handler(i);
StackTesting.handler(strs);
StackTesting.handler(objs);
请注意,更强大的实现将Pattern
在 Apex 内使用,这将代替.startsWith
和.endsWith
用于确定jsonString
是数组还是对象。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句