java - Is there a way to recognise a Java 16 record's canonical constructor via reflection?
问题描述
Assuming I have a record like this (or any other record):
record X(int i, int j) {
X(int i) {
this(i, 0);
}
X() {
this(0, 0);
}
X(String i, String j) {
this(Integer.parseInt(i), Integer.parseInt(j));
}
}
Is there a way to find this record's canonical constructor via reflection, i.e. the one that is implicitly declared in the RecordHeader
?
解决方案
Try this
static <T extends Record> Constructor<T> canonicalConstructorOfRecord(Class<T> recordClass)
throws NoSuchMethodException, SecurityException {
Class<?>[] componentTypes = Arrays.stream(recordClass.getRecordComponents())
.map(rc -> rc.getType())
.toArray(Class<?>[]::new);
return recordClass.getDeclaredConstructor(componentTypes);
}
And
Constructor<X> c = canonicalConstructorOfRecord(X.class);
X x = c.newInstance(1, 2);
System.out.println(x);
Output
X[i=1, j=2]
推荐阅读
- c# - UWP XAML:使用 FontIcon 和 HamburgerMenuItem 的自定义字体不呈现字形
- mdx - MDX 过滤器和日期范围问题
- r - 从 optim 调用 Rcpp 函数
- rest - TensorFlow Serving REST API 的正确负载
- spring-boot - Spring Boot 应用程序的 Bean 验证失败
- python - 如何将字符向量与方阵连接起来
- tensorflow - 张量流。针对特定任务的多对象检测
- php - Sphinx(searchd)无法找到新索引的文档
- python - 当两个用户同时输入时,SQL 会覆盖数据(Python)
- r - 从R中列表列中的所有列表中删除特定数字