确定构造函数中的哪个参数用于设置类中的特定字段? [英] Determine Which Parameter in Constructor was used to Set a Specific Field in Class?
问题描述
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..
谢谢
推荐答案
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屋!