Java反编译代码对齐
使用反编译的代码作为jar包源码进行调试时,经常会遇到的情况是反编译后的源码之在注释里包含行号,但是与代码所在行经常对应不上。这个时候,就有必要对代码进行对齐了。
1 public class Reorg { 2 public static void main(String[] args) throws IOException { 3 File file = new File("D:\\OpenSource\\lib\\framework\\frameworkTest"); 4 doReorg(file); 5 } 6 7 public static void doReorg(File file) throws IOException { 8 System.out.println("搜索路径:" + file.getPath()); 9 if (file.isDirectory()) { 10 File[] javaFiles = file.listFiles(new FilenameFilter() { 11 @Override 12 public boolean accept(File dir, String name) { 13 if (name.endsWith(".java")) 14 return true; 15 return false; 16 } 17 }); 18 19 for (File javaFile : javaFiles) { 20 ReorgJavaFile.reorgFile(javaFile); 21 } 22 23 24 File[] paths = file.listFiles(new FileFilter() { 25 @Override 26 public boolean accept(File pathname) { 27 if (pathname.isDirectory()) 28 return true; 29 return false; 30 } 31 }); 32 33 for (File path : paths) { 34 doReorg(path); 35 } 36 } 37 } 38 39 }
1 public class ReorgJavaFile { 2 private static final Pattern p = Pattern.compile("/\\*\\s*(\\d+)\\s*\\*/"); 3 4 public static void reorgFile(File f) throws IOException { 5 System.out.println("检查文件:" + f.getPath()); 6 7 int a = 0; 8 BufferedReader r = new BufferedReader(new FileReader(f)); 9 StringBuilder sb = new StringBuilder(); 10 11 12 String line; 13 while ((line = r.readLine()) != null) { 14 15 a++; 16 Matcher m = p.matcher(line); 17 if (m.find()) { 18 int num = Integer.valueOf(m.group(1)); 19 if (num < a) { 20 System.out.print("\t"); 21 System.out.println(f.getPath()); 22 System.out.print("\t"); 23 System.out.println("In line " + a + ", src file line is " + num); 24 } else if (num > a) { 25 while (num != a) { 26 sb.append("\n"); 27 a++; 28 } 29 } 30 } 31 32 sb.append(line).append("\n"); 33 34 } 35 36 r.close(); 37 38 BufferedWriter w = new BufferedWriter(new FileWriter(f)); 39 w.write(sb.toString()); 40 41 w.flush(); 42 w.close(); 43 } 44 45 }
不过此代码只能对反编译代码进行部分对齐,仍有一些地方需要人工进行对齐。