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

将对象从对象数组动态强制转换为枚举中可用的相应类

  •  0
  • bashint  · 技术社区  · 7 年前
    public class A {
         private String property;
         public String getProperty() {
              return property;
         }
    }
    public class B {
         private String property;
         public String getProperty() {
              return property;
         }
    }
    

    类似地,定义了C类和D类。(省略其他逻辑和复杂性)

    然后创建这些类名的枚举。[简单的类名或规范的类名我可以毫无问题地添加]

    public enum ClassNameEnum{ A, B, C, D }
    

    在另一个类中,我有一个对象数组,其中包含枚举中任何类的实例。

    我的目标: 获取对象数组中的每个元素,将它们转换为myEnum中的一个类名,并执行方法调用。

    到目前为止我所做的一切。 (1) 循环遍历对象数组,并使用if-else梯形图检查实例。如果匹配,施放并执行操作[工作但丑陋]

    (2) 改进:

    public class ImplClass {
        public static void main(String[] args)
        {
            List<Object> objectList = new ArrayList<Object>();
            objectList.add(new B());
            objectList.add(new D());
            objectList.add(new A());
    
            for (Object object : objectList) {
                Arrays.asList(ClassNameEnum.values()).stream()
                .filter(e -> obj instanceof e)   // Error here: e cannot be resolved to a type
                .map(e -> (e)obj)
                .map("Call getProperty() on the casted object and return the string"); // This is what I want to do
            }
        }
    }
    

    提前感谢

    2 回复  |  直到 7 年前
        1
  •  0
  •   Adrian    7 年前

    您可以将类存储到如下结构中,而不是枚举:

    class ClassInfo<T> {
        private final Class<T> clazz;
        private final Function<T, String> function;
    
        // all args constructor here
    
        String castAndApply(Object obj) {
            return function.apply(clazz.cast(obj));
        }
    }
    

    然后创建地图,例如:

    Map<Class, ClassInfo> classInfos = Map.of(
      A.class, new ClassInfo<>(A.class, A::getA),
      B.class, new ClassInfo<>(B.class, B::getB),
      C.class, new ClassInfo<>(C.class, C::getProperty)
    );
    

    下面是用法:

    objectList.stream()
            .filter(obj -> classInfos.containsKey(obj.getClass()))
            .map(obj -> classInfos.get(obj.getClass()).castAndApply(obj))
            .forEach(System.out::println);
    
        2
  •  0
  •   Mạnh Quyết Nguyễn    7 年前

    由于要从所有对象调用公共方法,因此在此处创建接口是有意义的。

    public interface Property {
       String getProperty();
    }
    

    在你的课堂上:

    public class A implement Property {
       private String property;
    
       @Override
       public String getProperty() {
              return property;
       }
    }
    

    尝试按对象的接口引用存储对象:

    List<Property> objectList = new ArrayList<>();
    objectList.add(new A());
    objectList.add(new B());
    ...
    

    最后:

    objectList.forEach(o -> System.out.println(o.getProperty()));