代码之家  ›  专栏  ›  技术社区  ›  souki

以通用方式根据值返回对象

  •  1
  • souki  · 技术社区  · 7 年前

    我有很多课 都继承自同一个类 :

    public class A
    {
      ...
    }
    
    public class AA extends A
    {
      ...
    }
    
    public class AB extends A
    {
      ...
    }
    
    public class AC extends A
    {
      ...
    }
    

    然后在代码的其他部分中,根据发送给该函数的值,我希望返回一个子类,如下所示:

    public A getChild(int value, Object foo)
    {
        switch(value)
        {
            case 0: {
                return new AA(foo);
            }
            case 1: {
                return new AB(foo);
            }
            case 2: {
                return new AC(foo);
            }
            default: {
              return new AA(foo);
            }
        }
    }
    

    在这个例子中,我只有三种类型的孩子。但我可以说其中30个 switch 声明将变得巨大。

    有没有其他方法可以做同样的事情 转换 这样的陈述会更通用吗?就像C语言中的函数指针?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Eran    7 年前

    您可以使用整数值到函数接口的映射,这些函数接口创建 A :

    Map<Integer,Function<Object,A>> map = new HashMap<>();
    map.put(0,f -> new AA(f));
    map.put(1,f -> new AB(f));
    ...
    

    然后按如下方式使用映射:

    public A getChild(int value, Object foo) {
        return map.getOrDefault(value, f -> new AA(f)).apply(foo);
    }
    
        2
  •  1
  •   0bot    7 年前

    在Java中,函数指针在C.中有类似的概念。 可以使用Java反射(但效率不高):

    public A getChild(String className, Object foo)
    {
       Class c = Class.forName(className);
       return (A) c.newInstance(Object foo);
    }
    

    并且可以使用映射来保持“int value”和“string classname”之间的关联。 但是这个解决方案没有效率! 相反,您可以使用由eran建议的函数映射。