This is why advanced fighter jets still carry guns
When Maverick told Goose his quarry was too close for missiles, and he was switching to guns, the Navy was still flying the F-14 Tomcat, a twin-engine interceptor whose first flight was in 1970. Today's newest advanced fighter jets, the F-22 and F-35 took their first flights in 1997 and 2006, respectively and can hit targets miles away, before the enemy will ever see them. So why do they still carry internally-mounted guns? The short answer is that fighter pilots want them.
In the air war over Vietnam, American pilots took a hard lesson while engaging a skilled enemy air force with planes on par with those in the American arsenal at the time. F-4 Phantoms, while being fast and powerful, were heavy, and going up against the MiG-19 and MiG-21 could often find themselves struggling to get out of the kill zone, unable to respond in kind because of the lack of a close-range weapon.
They needed onboard internal guns.
Just like in the days of the Vietnam War, many missiles have a minimum kill range. If an enemy fighter can get inside that range, even a fifth-generation fighter can find itself in deep trouble if it has no means of defending itself. Today's fighters may only carry enough ammunition for a few seconds burst of fire, but the technology in both targeting and individual rounds is far greater than in days gone by. A one-second burst from the onboard guns of an F-22 or F-35 is dozens of large explosive rounds on a target, more than enough to make a few passes at a target or bring down an enemy aircraft.
The enemy could be just as skilled as any American pilot, that's something the U.S. military can't plan for. What they can plan for is to fight the same technology used by the U.S. and its Western allies. The DoD has to assume they could be going up against advanced fighter jets comparable to the F-22 and F-35. If a Chinese J-20 can defeat missile targeting and get in close to one of ours, the pilot will likely need to hit his target at close range, using a weapon he can point.