V(D)J recombination
The details are very complex. The system makes sequences of amino acids which bind on to the corresponding sequences of infective agents. The system also recognises  "altered self cells" as seen in cancer.