Java: Alternative to passing “this” as constructor argument in order to reference creating object

前端 未结 3 1335
轮回少年
轮回少年 2021-02-14 07:05

I\'ve spent a while thinking about different solutions that the one I went for as I\'ve read around (I am not really experienced with Java yet) that using this for a constructor

3条回答
  •  猫巷女王i
    2021-02-14 07:30

    As long as it remains the only thing you do in the JobGroupMod constructor is is fairly safe as long as you understand the ramifications. There's a lot of Java code in the real world that does this. It's still not something you really want to do, especially when you start talking about multithreading and concurrency.

    The danger is passing this to something else before an object is fully constructed. If the constructor were to throw an exception after you did this and not fully construct, you could have a nasty problem. If another thread were to access the object you passed this to before it was fully constructed, you'd have a nasty problem.

    What you'll often find in Java is people using a factory pattern to avoid this, an "init" type method, or dependency injection.

提交回复
热议问题