顶点集:当您不知道数据集的数据类型时,如何遍历该集?



Set 不能像列表一样强制转换为一组对象。因此,如果您有一个可以接受任何对象的方法,例如:

public void handler(Object any_var_including_a_set)

有没有办法在不知道集合所持有的数据类型的情况下动态迭代集合的内容?

在 Apex 中没有Object.getClass()的概念;另一种方法是将instanceof与一组已知的类型一起使用。

下面是修改后的handler,它使用 JSON.serialize ,然后确定ofAnyType是数组、对象还是其他一些原语。

假设一个数组(Set或 Apex 中的List(,它可以被强制转换为 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);
            }
        }
    }
}

为了快速测试,我在StackTesting课上保存了handler。您可以使用下面的代码执行匿名 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);

请注意,更健壮的实现将使用 Apex 中的Pattern,这将取代.startsWith.endsWith来确定jsonString是数组还是对象。

最新更新