【问题标题】:Apex Set: How to iterate through a set when you don't know it's data type?Apex Set:当你不知道它的数据类型时如何迭代一个集合?
【发布时间】:2017-04-09 20:27:10
【问题描述】:

集合不能像列表一样被转换为对象集合。因此,如果您有一个可以采用任何对象的方法,例如:

public void handler(Object any_var_including_a_set)

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

【问题讨论】:

    标签: apex


    【解决方案1】:

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

    下面是修改handler,使用JSON.serialize,然后判断ofAnyType是数组、对象还是其他原语。

    假设一个数组(Apex 中的Set 或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);
                }
            }
        }
    }
    

    为了快速测试,我将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);
    

    请注意,更强大的实现将在 Apex 中使用 Pattern,这将代替 .startsWith 和 .endsWith 来确定 jsonString 是数组还是对象。

    【讨论】:

    • 谢谢罗杰!如此有趣的工作,这正是我想要的。
    猜你喜欢
    • 2012-06-15
    • 2011-04-01
    • 1970-01-01
    • 2019-12-14
    • 1970-01-01
    • 1970-01-01
    • 2017-05-25
    • 2015-08-16
    • 1970-01-01
    相关资源
    最近更新 更多