【问题标题】:Put dynamic objects to a data structure将动态对象放入数据结构
【发布时间】:2015-04-18 06:29:46
【问题描述】:

是否可以放置一个对象(可以是任何类,如原始类、盒装类或自定义类)并像自定义类一样获取它?

例如;

boolean isPossible;
MyCustomClass mCustomClass;

mSet.put(isPossible);
mSet.put(mCustomClass);

然后像访问它

mSet.isPossible;
mSet.mCustomClass;

或类似的东西。 我需要一个真正用户友好的结构来设置类之间共享的对象。

谢谢

【问题讨论】:

  • 不,不是真的,因为dot 表示法是类的调用成员,正如类中定义的那样。一旦你创建了类,你唯一能dot 的就是定义的成员。你能做的最好的就是mSet.get("isPossible")
  • 我已经按照你说的做到了。如果我使用代码生成呢?
  • 我不知道。对不起
  • 为什么还要把它放到mSet 中呢?您可以以isPossible 和myCustomClass 的身份访问课程,无需任何修饰。
  • 因为devoper可以把任何对象设置在运行时甚至不存在。我想让他/她轻松恢复。

标签: java android data-structures architecture dataset


【解决方案1】:

Visitor pattern可以帮到你

这有点像样板,但它允许您将不同的代码应用于不同类型的对象。

更现代的解决方案是使用 Scala 和模式匹配。

但是,您真的应该考虑坚持使用几个强制转换和 instanceof-s。

另一种解决方案是将所有内容都放在一个类中,就像 Jackson 的 JsonNode 那样。

【讨论】:

  • 非常感谢。我研究它们。
【解决方案2】:

正如@user1445898 所述,使用强制转换和instanceof,您可以使用通用Object 实例的HashSet,并根据需要根据集合中的内容进行强制转换/取消装箱。

我只是把这个简单的例子放在一起:

import java.util.HashSet;

public class HashSetTest
{
  public static void main(String[] args)
  {
    HashSet<Object> set = new HashSet<Object>();

    CustomClass myObject = new CustomClass("Custom Class Instance");

    set.add(new Integer(1));
    set.add(new Integer(2));
    set.add(new Double(3.123));
    set.add(myObject);


    for (Object o: set){
      if (o instanceof Integer){
        int i = ((Integer)o);  //unbox
        System.out.println("Integer: " + i);

      }
      else if (o instanceof Double){
        double d = ((Double)o); //unbox
        System.out.println("Double: " + d);

      }
      else if (o instanceof CustomClass){
         System.out.println("CustomClass: " + myObject);

      }
    }

  }
}

public class CustomClass
{
  private String message;

  public CustomClass(String input)
  {
    message = input;
  }
  public String toString()
  {
    return message;
  }
}

输出:

CustomClass: Custom Class Instance
Integer: 1
Integer: 2
Double: 3.123

【讨论】:

  • 要恢复数据,我必须使用这种结构进行循环。并且放置相同类型的对象使数据难以恢复。 :/ 我应该去地图吗?
  • @EmreAktürk 没错,这是一个缺点。根据您的需要,您可能需要选择其他选项。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-23
  • 2022-06-28
  • 2021-06-16
  • 2021-11-05
  • 2018-07-07
  • 2016-11-19
相关资源
最近更新 更多