获取嵌套类的内容
public class Foo { public static class MenuTreeRes { public static class MenuTreeRes_Message { } public static class MenuTreeRes_Data { } public static class MenuTreeRes_Menu { } } }
public class FooTest { public static void main(String[] args) { String s = "public class Foo {\r\n" + "\r\n" + " public static class MenuTreeRes {\r\n" + " public static class MenuTreeRes_Message {\r\n" + " }\r\n" + "\r\n" + " public static class MenuTreeRes_Data {\r\n" + " }\r\n" + "\r\n" + " public static class MenuTreeRes_Menu {\r\n" + " }\r\n" + " }\r\n" + "}"; String[] lines = s.split("\r\n"); String content = content(lines,"MenuTreeRes"); System.out.println(content); } private static String content(String[] lines, String className) { String target = String.format("public static class %s {", className).toLowerCase(); StringBuffer sb = new StringBuffer(); boolean started = false; int end = 0; for (String line : lines) { if(line.toLowerCase().contains(target)) { started = true; continue; } if(line.contains("public static class")) { end--; } if(line.trim().equals("}")) { end++; } if(end == 1) { break; } if(started) { sb.append(line).append("\r\n"); }else { continue; } } return sb.toString(); } }
思路:类似重入锁的加锁和解锁
结果:
public static class MenuTreeRes_Message { } public static class MenuTreeRes_Data { } public static class MenuTreeRes_Menu { }