gpt4 book ai didi

java - 如何让泛型函数根据Java中的输入获取对象属性

转载 作者:行者123 更新时间:2023-11-30 01:47:36 24 4
gpt4 key购买 nike

我有如下 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 的一些 if 条件获取一些用户详细信息。

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 获取用户对象。

我怎样才能做到这一点。

最佳答案

不确定我完全理解你的问题,但你可以这样做:

        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);
}

更新:

你可以像这样声明一个接口(interface)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);
}

关于java - 如何让泛型函数根据Java中的输入获取对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57369871/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com