确定构造函数中的哪个参数用于设置类中的特定字段? [英] Determine Which Parameter in Constructor was used to Set a Specific Field in Class?
问题描述
我正在开发自定义 Java 对象持久性框架,正如我最近在 这个问题.
I'm working on developing a custom Java object persistence framework as I recently discussed in this question.
我试图解决的一个问题是在构造函数参数和类中的相应字段之间强制使用统一的注释值.
One issue I am trying to solve is to force uniform annotation values accross constructor parameter and corresponding field in class.
是否可以通过反射知道使用构造函数中的哪个参数来设置类中的特定字段?例如,如果构造函数包含参数 String textXYZ
并且类包含字段 String textABC
并且在构造函数中我这样做: textABC = textXYZ
(所以字段/参数有不同的名字).是否可以通过反射知道字段 textABC
与构造函数参数 textXYZ
相关联?
Is it possible to know which parameter in constructor was used to set a specific field in class via reflection? For example, if constructor contains parameter String textXYZ
and class contains field String textABC
and in constructor I do: textABC = textXYZ
(so field/parameter have different names). Is it possible to know that the field textABC
is associated with the constructor parameter textXYZ
via reflection?
这将允许我只在字段上设置注释,然后推导出参数的注释值,反之亦然..
This would allow me to set annotation just on field and then deduce annotation value of parameter or vice versa..
谢谢
推荐答案
从 Java 7 开始,就有一个专门用于此目的的注释:ConstructorParameters
.当放置在构造函数上时,它显示该构造函数的参数如何对应于构造对象的 getter 方法.您可以反思地检查此注释,然后推断哪些字段是相关的.当然,没有人强制对构造函数进行注释,但这是关联字段和 ctor 参数的唯一标准方法.许多工具,如 Jackson、Jsonb 等,都有自己的注释用于相同的目的.
Since Java 7, there's an annotation exactly for that purpose: ConstructorParameters
. When placed on a constructor it shows how the parameters of that constructor correspond to the constructed object's getter methods. You can reflectively inspect this annotation and then deduce what fields are related.
Of course, no one is forcing the constructor to be annotated, but that's the only standard way to correlate the fields and the ctor params. Many tool, like Jackson, Jsonb etc have their own annotations for the same purpose.
这篇关于确定构造函数中的哪个参数用于设置类中的特定字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!