but for something like COBOL you could end up doing it for some years and then the legacy system is shut down and nobody wants to give you anything but a junior non-COBOL position.
You think that a systems migration won't need your legacy skills? You think that you won't pick up the skills for the new system during the migration?
Here's a more likely scenario: you do COBOL for 5 years and learn the entire problem domain that the COBOL system services. When the migration occurs with Java your knowledge will be indispensable, and you'll no doubt learn Java in the two years the migration takes to complete. At the end of the migration, you are still the expert in the problem and have new Java skills to apply your expertise.
It's exceptionally unlikely that the migration from COBOL will be so fast that you won't be able to learn the new implementation technology.