Remove code blocks from PSIMethod in . class file

已回答

Hi guys,

I now need to delete all code blocks for methods in .class file which from import list,  retaining only the structure and sending it to the backend service.
For example:

public class MyUtil {
    public static DateTime date() {
        return new DateTime();
    }
    public static int thisMinute() {
        return minute(date());
    }
}

Change to:

public class DateUtil {
    public static DateTime date() {}
    
    public static int thisMinute() {}
}

-------------------------------------------------------------------------------

My current implementation:

public static String getImportStructure(PsiFile javaFile) {
    StringBuilder sb = new StringBuilder();
    
    for (PsiImportStatementBase importStatement : javaFile.getAllImportStatements()) { // Simplified as an example
        PsiElement element = importStatement.getImportReference().resolve();
        sb.append(removeMethodBody(element.getContainingFile()));
    }
    
    return sb.toString();
}

public static String removeMethodBody(PsiFile classFile) {
    String text = classFile.getText();

    PsiMethod[] methods = ((PsiClass) classFile.getFirstChild()).getMethods(); // Simplified as an example
    for (int i = methods.length - 1; i >= 0; i--) {
        // getCodeBlock
        PsiCodeBlock psiCodeBlock = methods[i].getBody(); // it prints null!!!!!!!!

        // codeBlockRange
        int start = psiCodeBlock.getLBrace().getTextOffset() + 1;
        int end = psiCodeBlock.getRBrace().getTextOffset();

        // removeMethodBody
        text = text.substring(0, start) + text.substring(end);
    }

    return text;
}

-------------------------------------------------------------------------------
But I found that the getBody of PSIMethod in .class file always returns null.

This leads to bugs in the above implementation.

 

Any suggestions?

Thanks.

 

0

Hi,

This is expected that methods in compiled classes return null body. It is documented in com.intellij.psi.PsiMethod#getBody.

I suggest checking what the getText methods return. Maybe it will be exactly what you need, so methods without bodies.

0

I'm going to give it a try now.
Thank you.

0

请先登录再写评论。