[英]Get List of MethodHandle from key fields which are private in an object
I have a list of object with many private fields and I would want to group them according to a few key fields that come from a database. 我有一个包含许多私有字段的对象列表,我想根据数据库中的一些关键字段对它们进行分组。 The method class is in another package.
方法类在另一个包中。 My object would look like
我的对象看起来像
public class MyObject {
private String field1;
private String field2;
private String field3;
private Integer field4;
...}
and the key fields could be any combination of the fields in the Object 并且关键字段可以是对象中字段的任意组合
I have tried to get a list of MethodHandle for key fields. 我试图获取关键字段的MethodHandle列表。 This list of MethodHandle would be later streamed and invoked for Collectors.groupingBy to form a Map.
该MethodHandle列表将在以后流化并为Collectors.groupingBy调用以形成Map。
private static Map<List<String>, List<MyObject>>
groupListBy(List<MyObject> objList, String[] keyFields) {
final MethodHandles.Lookup lookup = MethodHandles.lookup();
List<MethodHandle> handles = Arrays.stream(keyFields)
.map(field -> {
try {
// What I tried by didn't work
// Field f = objList.get(0).getClass().getDeclaredField(field);
// f.setAccessible(true);
return lookup.findGetter(MyObject.class, field, String.class);
} catch (Exception e) {
throw new RuntimeException(e);
}
}).collect(Collectors.toList());
.
.
};
However, there would be an Illegal Access Exception for accessing a private member when forming a list of MethodHandle for the private fields in the MyObject. 但是,在为MyObject中的私有字段形成MethodHandle列表时,访问私有成员会出现非法访问异常。
May I know how can I access those fields. 我可以知道如何访问这些字段。 Thank you!
谢谢!
Edit: I know there is a method called privateLookupIn() in Java 9, but I'm using Java 8 currently. 编辑:我知道Java 9中有一个称为privateLookupIn()的方法,但是我目前正在使用Java 8。
I looked through some other answers and came up with this 我浏览了其他一些答案,并提出了
final MethodHandles.Lookup lookup = MethodHandles.lookup();
Object obj = new Object();
List<MethodHandle> handles = Arrays.stream(keyFields)
.map(field -> {
try {
PropertyDescriptor pd = new PropertyDescriptor(field, Object.class);
Method getter = pd.getReadMethod();
getter.setAccessible(true);
MethodHandle pmh = lookup.unreflect(getter);
return pmh;
} catch (Exception e) {
throw new RuntimeException(e);
}
}).collect(Collectors.toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.