我已经有以下代码,但是TypeDeclaration中的setName不能将String作为参数,它需要一个SimpleName对象,而我不知道如何获取SimpleName对象,也许这个想法是错误的?毕竟,我需要更改Java类名称,有什么解决方案吗?

ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setSource(str.toCharArray()); //str is the code of .java file
parser.setKind(ASTParser.K_COMPILATION_UNIT);

final CompilationUnit cu = (CompilationUnit) parser.createAST(null);

List types = cu.types();
TypeDeclaration typeDec = (TypeDeclaration) types.get(0); //typeDec is the class
System.out.println("className:" + typeDec.getName());

//SimpleName sn = new SimpleName();
//sn.setIdentifier("aqaa"); //change the class name to "aqaa", but this code fails
//typeDec.setName(sn);


如果我们将最后三个句子更改为:

SimpleName sn = typeDec.getName();
sn.setIdentifier("aqaa");
typeDec.setName(sn);


最后一个setName将引发异常:

importName: java.awt.BorderLayout start: 61 length: 29Exception in thread "main" java.lang.IllegalArgumentException
className: NI

    at org.eclipse.jdt.core.dom.ASTNode.checkNewChild(ASTNode.java:1873)
    at org.eclipse.jdt.core.dom.ASTNode.preReplaceChild(ASTNode.java:1935)
    at org.eclipse.jdt.core.dom.AbstractTypeDeclaration.setName(AbstractTypeDeclaration.java:155)
    at org.catr.JavaRefiner.parse(JavaRefiner.java:52)
    at org.catr.JavaRefiner.ParseFilesInDir(JavaRefiner.java:130)
    at org.catr.JavaRefiner.main(JavaRefiner.java:142)


也许我应该发布整个课程,以便你们可以自己尝试代码:)

package org.catr;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ImportDeclaration;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.core.dom.VariableDeclarationStatement;

public class JavaRefiner
{
static int a;

//use ASTParse to parse string
public static void parse(String str)
{
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(str.toCharArray());
    parser.setKind(ASTParser.K_COMPILATION_UNIT);

    final CompilationUnit cu = (CompilationUnit) parser.createAST(null);

    List imports = cu.imports();
    ImportDeclaration importDec = (ImportDeclaration) imports.get(0);

    System.out.println("importName: " + importDec.getName() + " start: " + importDec.getStartPosition() + " length: " + importDec.getLength());

    List types = cu.types();
    TypeDeclaration typeDec = (TypeDeclaration) types.get(0);
    System.out.println("className: " + typeDec.getName());

    SimpleName sn = typeDec.getName();
    sn.setIdentifier("NII");
    typeDec.setName(sn);

    cu.accept(new ASTVisitor()
    {
        Set<String> names = new HashSet<String>();

        public boolean visit( VariableDeclarationStatement state)
        {
            List<VariableDeclarationFragment> frags = state.fragments();
            Type type = state.getType();
            System.out.println("Type:\t\t\t'" + type + "'\t\t\tat line " + cu.getLineNumber(type.getStartPosition()));
            for (VariableDeclarationFragment frag: frags)
            {
                visit2(frag);
            }
            return false;
        }

        public boolean visit2(VariableDeclarationFragment node)
        {
            SimpleName name = node.getName();

            this.names.add(name.getIdentifier());
            System.out.println("Declaration:\t\t'" + name + "'\t\t\tat line "
                    + cu.getLineNumber(name.getStartPosition()));
            return false; // do not continue
        }

        public boolean visit(SimpleName node)
        {
            if (this.names.contains(node.getIdentifier()))
            {
                System.out.println("Usage:\t\t\t'" + node + "'\t\t\tat line "
                        + cu.getLineNumber(node.getStartPosition()));
            }
            return true;
        }
    });

}

//read file content into a string
public static String readFileToString(String filePath) throws IOException
{
    StringBuilder fileData = new StringBuilder(1000);
    BufferedReader reader = new BufferedReader(new FileReader(filePath));

    char[] buf = new char[1024];
    int numRead = 0;
    while ((numRead = reader.read(buf)) != -1)
    {
        //System.out.println(numRead);
        String readData = String.valueOf(buf, 0, numRead);
        fileData.append(readData);
        buf = new char[1024];
    }

    reader.close();

    return  fileData.toString();
}

//loop directory to get file list
public static void ParseFilesInDir() throws IOException
{
    File dirs = new File(".");
    String dirPath = dirs.getCanonicalPath() + File.separator + "data" + File.separator;

    File root = new File(dirPath);
    //System.out.println(rootDir.listFiles());
    File[] files = root.listFiles ( );
    String filePath = null;

     for (File f : files )
     {
         filePath = f.getAbsolutePath();
         if (f.isFile())
         {
             parse(readFileToString(filePath));
         }
         else
         {
             a = 0;
             a = a + 1;
         }
     }
}

public static void main(String[] args) throws IOException
{
    ParseFilesInDir();
}


}

最佳答案

使用以下代码:

List types = cu.types();
TypeDeclaration typeDec = (TypeDeclaration) types.get(0); //typeDec is the class
System.out.println("className:" + typeDec.getName());

SimpleName sn = typeDec.getName();
sn.setIdentifier("aqaa");
typeDec.setName(sn);

关于java - 如何使用Eclipse JDT API更改Java类名称?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22930026/

10-14 12:34
查看更多