Oliver
Posts: 12
Nickname: lazycat
Registered: Dec, 2002
|
|
Re: How to write a Java Program to analyse codes.
|
Posted: Jan 14, 2003 2:25 AM
|
|
//the sample code only solve the condition which the class keyword and the class name in one line.
import java.util.regex.*; import java.util.*; import java.io.*;
public class GetClassName{ private List classNameList; private String srcFileName; private BufferedReader in; public GetClassName(String srcFileName){ this.srcFileName = srcFileName; classNameList = new ArrayList(); try{ in = new BufferedReader( new FileReader(this.srcFileName)); } catch(FileNotFoundException e){ e.printStackTrace(); } } public List getClassName(){ String line; Pattern classPattern = Pattern.compile("class[ \\t]+([_$\\w]+)", Pattern.MULTILINE); Pattern commentBeginLikeC = Pattern.compile("[ \\t]*/\\*"); Pattern commentLikeCPP = Pattern.compile("[ \\t]*//"); Matcher m; try{ while((line = in.readLine()) != null){ m = commentLikeCPP.matcher(line);
//skip comments like CPP if(m.find()) continue; m = commentBeginLikeC.matcher(line); //skip comments like C if(m.find()) skipCommentLikeC(line); //replace string literal with empty string line = replaceWithEmptyString(line); m = classPattern.matcher(line); //find a class , get the name of the class if(m.find()){ String className = m.group(1); classNameList.add(className); } } } catch(IOException e){ e.printStackTrace(); } return classNameList; } public void skipCommentLikeC(String oneLine){ Pattern commentEndLikeC = Pattern.compile("\\*/[ \\t]*"); Matcher m = commentEndLikeC.matcher(oneLine); if(m.find()) return; else{ String line; try{
while((line = in.readLine()) != null){ m = commentEndLikeC.matcher(line); if(m.find()) return; } } catch(IOException e){ e.printStackTrace(); } } } public String replaceWithEmptyString(String line){ return line.replaceAll("\".*\"", "\"\""); } }
class TestGetClassName{ public static void main(String [] args){ GetClassName gn = new GetClassName("GetClassName.java"); System.out.println(gn.getClassName()); } }
|
|