That would indeed be illegal then as you are not allowed to distribute modified source code.
It is also not something we will be helping you with. Jarmodding is a disruptive way to make mods and not supported on this forum in any way.
Calling discard on an entity that is never even present in the world does nothing. Your renderer will still hold the reference to the entity and therefor prevent it from being garbage collected.
What you should do is check that the level is still the same (use an == comparison on the level instance, do not check the dimension). If it has changed, remove the old entity.
The version you are using is no longer supported on this forum.
Please update to a modern version of Minecraft to receive support.
Currently supported versions are 1.18.1/1.18.2 (Latest) and 1.16.5 (LTS).