如何在不使用 Java Reflection API 的情况下从 HashMap 中获取对象?

发布于 2024-12-25 11:46:51 字数 472 浏览 1 评论 0原文

假设我有一个 HashMap:

val userMap = new HashMap[String, String]
userMap += "username" -> "user"
userMap += "password" -> "pass"

和一个对象:

username:String = ""
password:String = ""

在不使用 Java Reflection API(带或不带注释)的情况下,将 HashMap 中的值放入对象的最佳方法是什么?

它可能类似于该问题: Scala - Lift - map a用于绑定的自定义装箱对象?

Let's say I have a HashMap:

val userMap = new HashMap[String, String]
userMap += "username" -> "user"
userMap += "password" -> "pass"

and an Object:

username:String = ""
password:String = ""

What would be the best way to put the values from the HashMap into the object, without using the Java Reflection API (with or without Annotations)?

It might be similar to that question: Scala - Lift - map a custom boxed object for bind?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

筑梦 2025-01-01 11:46:51

由于您不需要反射,因此无法自动匹配名称。但手动完成并不难。

鉴于

class User(val username: String = "", val password: String = "") {}

我会给

for {
  name <- userMap.get("username")
  pwd <- userMap.get("password")
} yield new User(name,pwd)

你一个 Option[User]Some 用户(如果它在该地图中),如果不在该地图中,则为 None

Since you don't want reflection, you can't match up the names automatically. But doing it manually isn't hard.

Given

class User(val username: String = "", val password: String = "") {}

I would just

for {
  name <- userMap.get("username")
  pwd <- userMap.get("password")
} yield new User(name,pwd)

which will give you an Option[User] with Some user if it is in that map, and None if not.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文