Java Reflection and the pain in Refactoring

后端 未结 9 1658
清歌不尽
清歌不尽 2021-02-08 14:25

Java Reflection provides a mechanism to introspect an Object at runtime. No second thoughts, this is a great feature, but it breaks all the Refactoring conventions!

Ther

相关标签:
9条回答
  • 2021-02-08 14:59

    You might be interested in using IntelliJ IDEA, which will also search for refactored class names in comments and string constants.

    0 讨论(0)
  • 2021-02-08 15:01

    Modern IDE's have the feature that when renaming a class, they will search for the fully qualified name in, for example, your xml files to try and rename any references you might have in those. Don't think it solves the problem - very often you don't absolutely reference class names.

    Also, that is why particular care and consideration must be exercised before you use it in your own code.

    But this problem with reflection is why using annotations is becoming more popular. The problem is reduced when using annotations.

    But let me say, as the previous post rightly points out, if you don't have a good safety net of unit tests, any kind of refactoring, whether you use a lot of reflection or not, is dangerous.

    0 讨论(0)
  • 2021-02-08 15:07

    What about taggin classes, methods, fields you know are accessed by reflection? The IDE could warn you when you change their names.

    0 讨论(0)
  • 2021-02-08 15:08

    As an aside, Reflection also causes issues if you want to protect your code via obfuscation. Typical obfuscation tools now require you to maintain a list of all files that you do not want obfuscated so that reflection from all the XML config files works properly.

    That said, A J2EE version of Eclipse IDE along with suitable plugins for the major frameworks like Hibernate, Spring etc will do a fairly good job of handling refactoring. Unit tests will reduce the testing cycle, but the concern is that sometimes the unit tests also depend on some XML configuration forcing you to use reflection. So it is possible to break unit tests along with your code while refactoring.

    0 讨论(0)
  • 2021-02-08 15:09

    We have actually developed an Eclipse plugin that takes care of this problem to a great extent. It is called RefaFlex: http://www.feu.de/ps/prjs/rf/

    0 讨论(0)
  • 2021-02-08 15:09

    Well, it's another opportunity for IDE makes to sell expensive premium versions which will recognize and refactor class names used in specific configuration files.

    Alternatively, such recurring cases can be handled by a test suite that performs sanity checking on such files, i.e. checks that all referred classes and methods exist. Such are specific to one file format, but are often relatively easy to write and can then be used to check all files of that format.

    But there is no general solution for the direct, "manual" use of the reflection API - which is why it's generally discouraged.

    0 讨论(0)
提交回复
热议问题