A rule-bending Brooklyn judge has injected needless courtroom drama into a seemingly open-and-shut case involving a man arrested for repeatedly raping a 9-year-old girl — by personally interviewing a potential trial witness with no lawyers around.

Brooklyn Supreme Court Justice ShawnDya Simpson secretly spoke with a guidance counselor expected to testify in the upcoming trial of Francisco Castro Rosas without the presence of prosecutors or a defense attorney.

Rosas did not deny having sex with the girl and instead told cops the 9-year-old took advantage of him and initiated all sexual encounters.

According to the Administrative Rules of the Unified Court System, “A judge shall not initiate, permit, or consider ex parte communications, or consider other communications made to the judge outside the presence of the parties or their lawyers concerning a pending or impending proceeding.”

“Judges have professional and ethical obligations and are bound by rules, like not doing private interviews with witnesses,” an affronted law enforcement source said in reaction to the incident, which all occurred off the record.

“It’s a shame Judge Simpson didn’t get that memo.”

Assistant District Attorney Frank DeGaetano asked Simpson to step aside Friday and transfer the case to another judge, saying it was now possible that Simpson herself could become a witness due to her puzzling interference.

“We are in the position now where the court has had an extrajudicial conversation with a witness in the case,” the prosecutor said, adding it could affect the ability of both the DA’s office and the defense team to effectively try the case. “And so we are asking that the matter be tried by a different court.”

“Well, that’s denied,” Simpson shot back.

Simpson, according to court transcripts, explained away her eyebrow-raising behavior by saying she wanted to review the victim’s school records to determine if the child was emotionally strong enough to testify against her alleged abuser.

Rosas stands charged with two counts of course of sexual misconduct against a child, and one count of endangering the welfare of a child.

“I was in bed, I woke up with her playing with my penis,” he told cops after his 2017 arrest, adding that the 9-year-old proceeded to have sex with him. “She took advantage of me while I was sleeping.”

If convicted, he faces up to 25 years behind bars.

Simpson and the Brooklyn DA’s office declined to comment.