java - 如何使用 Eclipse JDT API 更改 Java 类名?

标签 java eclipse

我已经有了如下代码,但是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); 

如果我们将最后 3 句改为:

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)

也许我应该发布整个类(class),这样你们就可以自己尝试代码:)

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/

相关文章:

java - 如何使用 Eclipse 在 Android 中实现/链接 Run Keeper API?

java - 在 webdriver 中维护浏览器 session

java - 如何使用 gitExtension 将存储库从 Linux 克隆到我的 Windows 桌面

java - 在 hadoop 中运行作业 - 错误

java - 将构建路径切换到 JDK 10 后 Eclipse 找不到 XML 相关类

java - Eclipse 没有编译我的 Groovy 文件

javascript - 在 testdata.properties 文件中显示非英语语言

java - Ant build.xml需要用户输入,但Eclipse没有tty

java - 如何在oracle兼容模式和hibernate中使用hsqldb获取序列的下一个值

java - 有没有办法让 Eclipse 显示类中变量中定义的方法而无需输入句点?