java反射创建字段/值哈希图
我需要创建实体中包含的字段/值的哈希图,因此我可以使用它们将它们替换为包含带有字段名称的标签的字符串。
我有这样的代码:
public static String replaceTags(String message, Map<String, String> tags) ...
它将 message 中找到的所有标签替换为 tags 中的等效值,但为了构建地图表,我需要获取“任何”实体并能够从该实体创建映射。那么,我怎样才能做到这一点呢?获取一个例程,在该例程中发送实体并返回包含所有字段和值的映射。
public static Map<String, String> getMapFromEntity(Object entity){
Map<String, String> map = new HashMap<String, String>();
...?????
return map;
}
我知道我可以使用反射,这是我发现完成此任务的唯一方法,但是还有其他方法可以完成相同的任务吗?我的意思是更有效的方法。
谢谢。
I need to create a Hashmap of field/values contained in an Entity, so I can can use them to replace them in a String containing tags with the field names.
I have this code:
public static String replaceTags(String message, Map<String, String> tags) ...
Which replaces all tags found in message for the equivalent values in tags, but in order to build the Map table I need to take "any" Entity and be able to create a Map from the Entity. So, how could I make that possible? to get a routine where I send the Entity and get as return a Map with all the fields and values.
public static Map<String, String> getMapFromEntity(Object entity){
Map<String, String> map = new HashMap<String, String>();
...?????
return map;
}
I know I could use reflection and this is the only approach I have found to get this done, but is there any other way to accomplish the same?, I mean a more efficient way.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
O,您的实体应该是您的类的对象,而不是您的类本身。
如果您的字段是私有的并且您有它们的 getter,您应该使用 getMethods() 并检查方法名称是否以“get”前缀开头。如下所示:
O, and your entity should be an object of your class, not your class itself.
If your fields are private and you have getters for them, you should use getMethods() and check if method name starts with "get" prefix.Like this:
如果你只想得到一张地图,为什么不使用像杰克逊这样的文学作品,那么你可以简单地像这样转换它
Map map = new ObjectMapper().convertValue(object, Map.class);
If all you want to get out of this is a map, why not use a literary like Jackson, then you can simply convert it like this
Map map = new ObjectMapper().convertValue(object, Map.class);
据我所知,反射是实现此目的的唯一方法,除非您想要构建地图的类实现某个接口,并且提取地图的代码知道该接口。
As far as I know, reflection is the only way to accomplish this, unless the class(es) you want to build the map from implement some interface, and your code extracting the map is aware of this interface.