猿问

Java 仅获取某些对象字段

我有一个看起来像这样的 POJO:


public class Task {

    private TaskData taskData;


    String id;

    private int status;

    private int success;

    private int error;

}


class TaskData {

    transient LinkedList<String> list0;

    transient LinkedList<String> list1;

}

中的列表TaskData可能很大(超过 100mb)。


从我获取所有对象时,Map<String, Task> tasksMap = new HashMap()我不希望TaskData包含/加载字段。我怎样才能实现它?


PS 与序列化无关。


更新: 通过“获取所有对象”我的意思是,例如:


class SomeClass {

   Map<String, Task> tasksMap = new HashMap()


   SomeClass() {

      //...initialize multiple tasks with huge list0, list1..

      // => add them all

      tasksMap.put("abc0", task);

      tasksMap.put("abc1", task);

      tasksMap.put("abc2", task);

      tasksMap.put("abc3", task);

   }


   Map<String, Task> tasksMap getMap() {

      // when i get all the map's objects, i want the received `Task` objects

      // to not have `TaskData` attribute


      return tasksMap;

   }

}


跃然一笑
浏览 260回答 2
2回答

杨__羊羊

给该字段一个默认值 null,然后稍后使用 setter 方法更新该值。public class Task {&nbsp; &nbsp; private TaskData taskData;&nbsp; &nbsp; String id;&nbsp; &nbsp; private int status;&nbsp; &nbsp; private int success;&nbsp; &nbsp; private int error;}class TaskData {&nbsp; &nbsp; transient LinkedList<String> list0 = null;&nbsp; &nbsp; transient LinkedList<String> list1 = null;&nbsp; &nbsp; public void setList0(LinkedList<String> list){&nbsp; &nbsp; &nbsp; &nbsp; list0 = list;&nbsp; &nbsp; }&nbsp; &nbsp; public void setList1(LinkedList<String> list){&nbsp; &nbsp; &nbsp; &nbsp; list1 = list;&nbsp; &nbsp; }}

人到中年有点甜

我认为另一种方法是创建一个浅拷贝方法,排除您不想要的字段,并在填充 Map 时使用它,例如:&nbsp; public Task shallowCopy() {&nbsp; &nbsp; Task newTask = new Task();&nbsp; &nbsp; newTask.id = id;&nbsp; &nbsp; newTask.status = status;&nbsp; &nbsp; ...&nbsp; &nbsp; return newTask;&nbsp; }
随时随地看视频慕课网APP

相关分类

Java
我要回答