使用Java反射不良做法吗? [英] Is using Java Reflection Bad Practice?

查看:91
本文介绍了使用Java反射不良做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为客户端构建一个应用程序,并且我需要能够通过字符串引用字段值,即用户使用字符串来定义他们想要更改其值的字段。 ,这是抽象框架的一部分,因此从技术上讲,我不知道他们希望更改的字段的名称。当然我可以使用哈希映射来做到这一点,但是我正在考虑使用Java反射,因为这允许字段保留为对象的字段,而不是将值编码为哈希映射。我在自己的个人工作中使用了反射,但是我想知道使用Java反射是否真的是不好的做法,我应该坚持使用hashmap方法。

I am building an application for a client and I am in the situation where I need to have the ability to reference a field value via a string, i.e the users uses a string to define which field they want to change the value of, this is part of an abstract framework so technically I don't know the name of the fields they desire to change. Of course I could do this using hash maps, but I am considering using java reflection as this allows the fields to stay as fields of the object rather than the values being coded into a hash map. I have used reflection for my own personal work, but I was wondering if using Java reflection is actually bad practice, and I should stick to the hashmap methodology.

(对于解决所描述的设计问题的任何其他建议,也应赞赏)

(Any other suggestions for solving the design problem described are also appreciated)

谢谢

推荐答案

问题本身是基于观点的,尽管我相信大多数人都同意您不能只说反射不好。有时,这是唯一的方法,这就是为什么许多库都使用反射的原因。有时这不是唯一的方法,但解决方法甚至会更糟。有时候,这不是唯一的方法,也不是最简单的方法,但是开发人员对反射的力量感到惊讶,无法直截了当地思考。

The question itself is opinion based, although I believe most will agree that you can't just say "reflection is bad". Sometimes it's the only way, which is why a lot of libraries use reflection. Sometimes it's not the only way, but a workaround would be even worse. Sometimes it's not the only way, and not the easiest way, but the developer is far too amazed at the power of reflection to think straight.

除了那最后一个有很多将反射作为解决方案的正当理由。

Except for that last one there are plenty of valid reasons to consider reflection as a solution.

这篇关于使用Java反射不良做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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