Java Reflection and the pain in Refactoring

后端 未结 9 1661
清歌不尽
清歌不尽 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 15:20

    Java reflection causes many of the same problems you get with dynamically typed languages such as Python and Ruby. In fact, one way to think about dynamically typed languages is that everything is called using reflection, and the languages just provide a nice, clean syntax for reflection.

    And yes, with dynamically typed languages (or heavy uses of reflection), refactoring is hard. You don't get the nice Eclipse refactoring capabilities. Instead, grep becomes your friend.

    From my experience, the best thing you can do is build yourself a good safety net of unit tests. That way, if you break some dynamic code during refactoring, at least you'll catch it quickly when you run the tests.

    If you're doing lots of statically typed code, you're in big trouble if you don't have a good base of unit tests. If you're doing lots of dynamically typed code (including code with lots of reflection), you don't have any hope of being successful without a good base of unit tests.

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

    Refactoring could be improved by introducing more "literals" in the language. E.g. imho .class literal are a great way to ensure compile-time safety of certain models. However the important thing to say here is that, sometimes, I want to lose compile-time safety. Strings are the most simple yet powerful way to express a loosely coupled contract between two layers since you can manipulate or match them against a regular expression, etc

    The real problem of reflection is the verbose use of the API. The is the major cost for flexibility.

    PS

    Project coin could introduce somewhere in the future some new language construct to enhance this area.

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

    You can avoid writing reflection API with dp4j.com when you know at compile time what you are looking for.

    About xml mappings, they are a pain, I also experienced with NetBeans Platform and less so with JPA2. The good news is that annotations are taking over, and this offers again compile-time checking. I'm not sure about Hibernate, but both JPA and NetBeans (more as of 7) offer annotation equivalents of xml mappings.

    I had also developed SqlWrapper to get away from using strings with JDBC. More sophisticated (and complicated) is JPA2's criteria API.

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