确定构造函数中的哪个参数用于设置类中的特定字段? [英] Determine Which Parameter in Constructor was used to Set a Specific Field in Class?

查看:95
本文介绍了确定构造函数中的哪个参数用于设置类中的特定字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个自定义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开始,就有一个专门用于此目的的注释:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆