使用辅助类使 JavaBean 的使用更加方便——这是某种习惯用法吗?

发布于 2024-12-15 00:34:25 字数 684 浏览 3 评论 0原文

在工作中,我经常需要处理大量使用 JavaBean 的第三方库。因为使用 JavaBeans(尤其是创建)非常乏味并且违反了干燥(大量复制),所以我经常编写一个帮助器类,以便能够以更“类似 oo”的方式创建 JavaBeans(即,将所有需要的信息传递到构造函数中) ),这样的东西

// left out the implementation of the method, just to give an idea
public class MyBean {
  public MyBean();

  public void setFoo(String foo);
  public void setBar(String bar);
}

public MyBeans {
  public static MyBean newMyBean(String foo, String bar);
}

现在,使用静态导入,我可以:

MyBean bean = newMyBean(foo, bar);

而不是:

MyBean bean = new MyBean();
bean.setFoo(foo);
bean.setBar(bar);

这是某种习惯用法吗,有什么缺点吗(我知道,静态导入有点争议),有没有任何 Maven 插件可以为我生成这些帮助类?

At work, I often have to deal with 3rd party libraries, which make heavy use of JavaBeans. Because working with JavaBeans (especially creation) is very tedious and violates dry (lots of replication), I often write a helper class to be able to create JavaBeans in more "oo-like" (i.e., pass all the needed information into the constructor), something like this

// left out the implementation of the method, just to give an idea
public class MyBean {
  public MyBean();

  public void setFoo(String foo);
  public void setBar(String bar);
}

public MyBeans {
  public static MyBean newMyBean(String foo, String bar);
}

Now, with using static imports, I can:

MyBean bean = newMyBean(foo, bar);

Instead of:

MyBean bean = new MyBean();
bean.setFoo(foo);
bean.setBar(bar);

Is this some sort of idiom, are there any downsides (I know, the static import is kinda controverse), and are there any Maven plugins which can generate these helper classes for me?

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

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

发布评论

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

评论(1

葬心 2024-12-22 00:34:25

据我所知,没有任何 Maven 插件可以为您创建这些工厂,但它是一个简单的代码生成库。它需要可配置来创建给定类的各种工厂,您想要设置哪些属性,但必须考虑类的具体情况。

由于配置需要(无论如何,正如我所看到的),我从来没有费心将我的实现包装到 Maven 插件中。我手动生成它们(以及流畅的界面选项),并且再也不会考虑它们。

在我看来,它们通常需要人工干预,因此不值得将这个过程进行自动化。只需将它们生成到普通的 src/main/java 树中并假装它们是您自己编写的。

I know of no Maven plugin that will create these factories for you, but it's a simple code generation library. It needs to be configurable to create various factories given a class, which properties you'd like to set, but must take class specifics into account.

Because of the configuration needs (as I see it, anyway) I've never bothered wrapping my implementations into a Maven plugin. I generate them manually (along with fluid interface options), and never think about them again.

IMO they usually require human intervention, so it's not worth Mavenizing the process. Just generate them into the normal src/main/java tree and pretend you wrote them yourself.

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