[英]How to make generic function get object properties based on input in Java
我有如下的Java實體
@Entity
@Table(name = "user", schema = "xxxx")
public class User extends AuditableBase<Long> {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = -5827659402853250569L;
public static final String FTL = "FTL";
/** The refer number. */
@Column(name = "reference_number")
private String referenceNumber;
/** The customer id. */
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "customer_id")
@Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED)
private Customer customer;
/** The load Notes. */
@OneToMany(cascade = CascadeType.ALL, mappedBy = "load")
@JsonBackReference
private Set<Notes> notes = new HashSet<>();
/** The customer location. */
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "customer_location_id")
@Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED)
private CustomerLocation customerLocation;
/** The invoice number. */
@Column(name = "invoice_number")
private String invoiceNumber;
// Lot going
/**
* Instantiates a new User.
*/
public User() {
super();
}
/**
* Instantiates a new User.
*
* @param id
* the id
*/
public User(Long id) {
super(id);
}
}
我在實體中有很多孩子,我正在從DAO調用中獲取對象
User user = userRepository.findById(userId);
現在,我想獲取一些用戶詳細信息,基於某些條件(如果條件引用到Map)。
Map<Integer, String> cc = new HashMap<Integer, String>();
cc.put(1, "getCustomer()");
cc.put(2, "getNotes()");
cc.put(3, "getCustomerLocation()");
cc.put(4, "getReferenceNumber()");
for (Entry<Integer, String> map : cc.entrySet()) {
user.map.getvalue();
}
我需要創建一個通用方法來基於地圖獲取用戶對象。
我怎樣才能做到這一點。
不確定我是否完全理解您的問題,但是您可以執行以下操作:
Map<Integer,Method> cc = new HashMap<>();
cc.put(1, User.class.getDeclaredMethod("getCustomer"));
cc.put(2, User.class.getDeclaredMethod("getNotes"));
cc.put(3, User.class.getDeclaredMethod("getCustomerLocation"));
cc.put(4, User.class.getDeclaredMethod("getReferenceNumber"));
for (Entry<Integer, Method> map : cc.entrySet()) {
Integer index = map.getKey();
Method getter = map.getValue();
Object value = getter.invoke(user);
doSomethingUsefulWith(index, value);
}
更新:
您可以像這樣聲明接口Getter
:
public interface Getter<T,R> {
public R get(T obj);
}
然后執行以下操作:
Map<Integer,Getter<User,?>> cc = new HashMap<>();
cc.put(1, (u) -> u.getCustomer().getName());
cc.put(2, (u) -> u.getNotes());
cc.put(3, (u) -> u.getCustomerLocation());
cc.put(4, (u) -> u.getReferenceNumber());
for (Entry<Integer,Getter<User,?>> map : cc.entrySet()) {
Integer index = map.getKey();
Getter<User,?> getter = map.getValue();
Object value = getter.get(user);
doSomethingUsefulWith(index, value);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.