EnumMap是否可以被视为Java Bean的合理替代品? [英] Might EnumMap be considered a reasonable alternative to Java beans?

查看:134
本文介绍了EnumMap是否可以被视为Java Bean的合理替代品?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好奇是否有人考虑使用EnumMap代替Java bean,尤其是值对象"(无行为)?在我看来,优点之一是可以从支持枚举的Enum直接访问属性"的名称,而无需进行反思,因此我认为它会更快.

Curious if anybody has considered using EnumMap in place of Java beans, particularly "value objects" (with no behavior)? To me it seems that one advantage would be that the name of a "property" would be directly accessible from the backing Enum, with no need for reflection, and therefore I'd assume it would be faster.

推荐答案

可能会比使用反射更快(我没有测量它,也没有在Google中找到任何指标);但是这种方法有很多缺点:

It may be a little faster then using reflection (I didn't measure it, didn't find any metrics in Google either); however there are big disadvantages to this approach:

  1. 您正在失去类型安全性.代替int getAge()String getName()的都是Object get(MyEnum.FIELD_NAME).那会在那里提供一些难看的代码和运行时错误.

  1. You're losing type safety. Instead of int getAge() and String getName() everything is Object get(MyEnum.FIELD_NAME). That'll provide for some ugly code and run-time errors right there.

我们喜欢并享受的所有Javabean精美功能(例如,属性级别的注释)都消失了.

All the javabean niceties we've come to love and enjoy (for example, property-level annotations) are gone.

由于您根本无法表现出任何行为,因此这种方法的适用性似乎相当有限.

Since you can have NO BEHAVIOR AT ALL, the applicability of this approach seems rather limited.

最重要的是-如果您确实确实需要所谓的:-)提高性能(您必须测量以证明它存在),在非常特定的情况下这可能是一种可行的方法.它是代替Javabeans的可行选择吗?肯定不是.

The bottom line is - if you really truly need that alleged :-) boost in performance (which you'll have to measure to prove it exists) this may be a viable approach under very specific circumstances. Is it a viable alternative to javabeans at large? Most certainly not.

这篇关于EnumMap是否可以被视为Java Bean的合理替代品?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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