如何在 java 中放入 hashmap 时从对象中排除 属性
how to exclude a property from object while putting into hashmap in java
假设,Employee
class 具有三个属性。
class Employee {
int id;
String name;
String team;
public Employee(){
this.id = id;
this.name = name;
this.team = team;
}
}
我想在放入 HashMap
之前从对象中删除 team
。
Map<Integer, Employee> empMap = new HashMap<>();
Employee e1 = new Employee(100, "John", "Dev");
Employee e2 = new Employee(101, "Mary", "Dev");
Employee e3 = new Employee(103, "Andy", "QA");
empMap.put(e1.getId(), e1);
empMap.put(e2.getId(), e2);
empMap.put(e1.getId(), e3);
empMap
中的值不应包含 team
属性。创建新对象是可行的,但实时成本很高。有没有办法在不创建新对象的情况下实现这一点。
正如您所提到的,一种选择是在没有团队的情况下创建新对象 属性。另一种是使用外观
public class MapEmpFacade extends Employee {
public MapEmpFacade(Employee emp) {
//define all methods to return the method results from emp, except for getTeam
}
public int getTeam() { return null; } //override getTeam
}
您可以检查您的设计以确保您需要 属性。
您在 map
中持有 Employee
引用,team
属性 在那里并且可能正确地表示 Employee
...您可以避免使用team
属性 ... 或者您可能想要 Person
class.
如果您正在使用某些框架中的这些实例来执行某些操作(例如:序列化、持久化等),它可能应该提供一种在您的对象中 ignore/skip a 属性 的方法。
假设,Employee
class 具有三个属性。
class Employee {
int id;
String name;
String team;
public Employee(){
this.id = id;
this.name = name;
this.team = team;
}
}
我想在放入 HashMap
之前从对象中删除 team
。
Map<Integer, Employee> empMap = new HashMap<>();
Employee e1 = new Employee(100, "John", "Dev");
Employee e2 = new Employee(101, "Mary", "Dev");
Employee e3 = new Employee(103, "Andy", "QA");
empMap.put(e1.getId(), e1);
empMap.put(e2.getId(), e2);
empMap.put(e1.getId(), e3);
empMap
中的值不应包含 team
属性。创建新对象是可行的,但实时成本很高。有没有办法在不创建新对象的情况下实现这一点。
正如您所提到的,一种选择是在没有团队的情况下创建新对象 属性。另一种是使用外观
public class MapEmpFacade extends Employee {
public MapEmpFacade(Employee emp) {
//define all methods to return the method results from emp, except for getTeam
}
public int getTeam() { return null; } //override getTeam
}
您可以检查您的设计以确保您需要 属性。
您在 map
中持有 Employee
引用,team
属性 在那里并且可能正确地表示 Employee
...您可以避免使用team
属性 ... 或者您可能想要 Person
class.
如果您正在使用某些框架中的这些实例来执行某些操作(例如:序列化、持久化等),它可能应该提供一种在您的对象中 ignore/skip a 属性 的方法。