代码:统计某个java类依赖其它的哪些类

主要功能是统计某个java类依赖了哪些其它的类,引用的次数是多少等等。

统计类ClassImportStatistic.java

package org.slive.project.style.classimport;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import org.slive.project.style.util.FileUtil;

public class ClassImportStatistic {

    private static final Pattern END_IMPORT = Pattern.compile("^(public(\\s)+)?(\\s)*(class)(\\s)+(.)+");

    /**
     * 用于统计有多少个引用类
     * @param prjPath
     * @return
     * @throws IOException
     */
    public static List<ImportClass> importStatistic(String prjPath, String filterName) throws IOException {
        List<File> filelists = new ArrayList<File>();
        FileUtil.justListFiles(filelists, prjPath, filterName);
        Map<String, ImportClass> classMap = new HashMap<String, ImportClass>();
        for (File file : filelists) {
            List<String> ret = FileUtil.readFileStrList(file);
            for (String s : ret) {
                s = s.trim();
                if (END_IMPORT.matcher(s).matches()) {
                    break;
                } else {
                    if (s.startsWith("import")) {
                        String importClass = s.replace("import", "").replace(";", "").trim();
                        if (classMap.containsKey(importClass)) {
                            classMap.get(importClass).incr();
                        } else {
                            ImportClass cr = new ImportClass();
                            cr.setClazz(importClass);
                            cr.incr();
                            classMap.put(importClass, cr);
                        }
                    }
                }
            }
        }
        Collection<ImportClass> values = classMap.values();
        List<ImportClass> ls = new LinkedList<ImportClass>(values);
        // 重新排序
        Collections.sort(ls);
        return ls;
    }
}

统计数据模型ImportClass.java:

package org.slive.project.style.classimport;

public class ImportClass implements Comparable<ImportClass> {

    private String clazz;

    private long time;

    public String getClazz() {
        return clazz;
    }

    public void setClazz(String clazz) {
        this.clazz = clazz;
    }

    public long getTime() {
        return time;
    }

    public void setTime(long time) {
        this.time = time;
    }

    public void incr() {
        time++;
    }

    @Override
    public int compareTo(ImportClass arg0) {
        if (arg0 == null) {
            return 0;
        }
        return (int) (arg0.getTime() - this.getTime());
    }

    @Override
    public String toString() {
        return "{\"className\":\"" + clazz + "\", \"importTime\":" + time + "}\r\n";
    }
}

读取FileUtil.java:

package org.slive.project.style.util;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * 处理文件公共类
 * @author Slive 2016年8月10日
 */
public class FileUtil {

    /**
     * 文件路径分隔符
     */
    public static final String SP = File.separator;

    /**
     * 换行分隔符
     */
    public static final String LINE_SP = System.lineSeparator();

    /**
     * 获取所有文件(不包括文件夹)
     * @param fileLists 缓存结果队列
     * @param topPath 起始路径,要求是文件夹
     */
    public static void justListFiles(List<File> fileLists, String topPath) {
        justListFiles(fileLists, topPath, null);
    }

    public static void justListFiles(List<File> fileLists, String topPath, String filterName) {
        if (topPath == null) {
            return;
        }

        File file = new File(topPath);
        if (!file.isDirectory()) {
            return;
        }

        File[] files = file.listFiles();
        if (files != null) {
            for (File f : files) {
                if (f.isDirectory()) {
                    justListFiles(fileLists, f.getAbsolutePath(), filterName);
                } else {
                    if (filterName != null) {
                        if (!f.getName().endsWith(filterName)) {
                            continue;
                        }
                    }
                    fileLists.add(f);
                }
            }
        }
    }

    /**
     * 读取文件内容
     * @param file
     * @return 返回String 列表
     * @throws IOException
     */
    @SuppressWarnings("unchecked")
    public static List<String> readFileStrList(File file) throws IOException {
        return (List<String>) readFile(file, true, null);
    }

    /**
     * 读取文件内容
     * @param file
     * @return 返回String 列表
     * @throws IOException
     */
    @SuppressWarnings("unchecked")
    public static List<String> readFileStrList(File file, String encoding) throws IOException {
        return (List<String>) readFile(file, true, encoding);
    }

    /**
     * 读取文件内容
     * 
     * @param file
     * @return 返回字符串
     * @throws IOException
     */
    public static String readFileStr(File file) throws IOException {
        return ((StringBuffer) readFile(file, false, null)).toString();
    }

    /**
     * 读取文件内容
     * 
     * @param file
     * @param encoding 编码,为空则使用默认
     * @return 返回字符串
     * @throws IOException
     */
    public static String readFileStr(File file, String encoding) throws IOException {
        return ((StringBuffer) readFile(file, false, encoding)).toString();
    }

    @SuppressWarnings("unchecked")
    private static Object readFile(File file, boolean retList, String encoding) throws IOException {
        InputStream fr = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            fr = new FileInputStream(file);
            if (encoding != null) {
                isr = new InputStreamReader(fr, encoding);
            } else {
                isr = new InputStreamReader(fr);
            }
            br = new BufferedReader(isr);
            String readLine = null;
            Object sbd = null;
            if (retList) {
                sbd = new ArrayList<String>();
            } else {
                sbd = new StringBuffer();
            }
            boolean isFirst = true;
            while ((readLine = br.readLine()) != null) {
                if (retList) {
                    ((ArrayList<String>) sbd).add(readLine);
                } else {
                    if (isFirst) {
                        ((StringBuffer) sbd).append(readLine);
                        isFirst = false;
                    } else {
                        ((StringBuffer) sbd).append(LINE_SP + readLine);
                    }
                }
            }
            return sbd;
        } catch (IOException e) {
            throw new IOException(e);
        } catch (Exception e) {
            throw new IOException(e);
        } finally {
            close(br);
            close(isr);
            close(fr);
            file = null;
        }
    }

    /**
     * 关闭
     * @param obj 关闭对象
     */
    public static void close(Closeable obj) {
        try {
            if (obj != null) {
                obj.close();
            }
        } catch (IOException e) {
            // 忽略
        }
    }
}

测试ClassImportStatisticTest.java:

package org.slive.project.style;

import java.io.IOException;
import java.util.List;

import org.slive.project.style.classimport.ClassImportStatistic;
import org.slive.project.style.classimport.ImportClass;

/**
 * 描述:
 * 
 */
public class ClassImportStatisticTest {

    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        String prjPath = "E:\\DevPrjs\\003_OpenSource";
        List<ImportClass> ls = ClassImportStatistic.importStatistic(prjPath, ".java");
        System.out.println(ls);
    }

}

运行结果:

[{"className":"java.io.IOException", "importTime":2093}

, {"className":"java.util.List", "importTime":1732}

, {"className":"java.util.Map", "importTime":1300}

, {"className":"junit.framework.TestCase", "importTime":1241}

, {"className":"org.junit.Assert", "importTime":1140}

, {"className":"java.util.ArrayList", "importTime":1122}

, {"className":"java.io.File", "importTime":975}

, {"className":"org.junit.Test", "importTime":958}

, {"className":"com.alibaba.fastjson.JSON", "importTime":837}

, {"className":"java.util.HashMap", "importTime":738}

, {"className":"java.util.Set", "importTime":662}

, {"className":"org.apache.tools.ant.BuildException", "importTime":585}

, {"className":"java.util.Iterator", "importTime":551}

, {"className":"java.io.InputStream", "importTime":550}

, {"className":"java.util.Collection", "importTime":496}

, {"className":"java.util.Collections", "importTime":484}

, {"className":"com.alibaba.dubbo.common.URL", "importTime":419}

, {"className":"java.util.Arrays", "importTime":398}

, {"className":"org.apache.tools.ant.Project", "importTime":370}

, {"className":"static org.junit.Assert.assertEquals", "importTime":367}

, {"className":"java.util.Date", "importTime":362}

, {"className":"java.lang.reflect.Method", "importTime":352}

, {"className":"java.nio.ByteBuffer", "importTime":336}

, {"className":"java.util.Enumeration", "importTime":334}

, {"className":"org.junit.Before", "importTime":325}

, {"className":"java.util.concurrent.TimeUnit", "importTime":322}

, {"className":"java.util.HashSet", "importTime":316}

, {"className":"java.io.Serializable", "importTime":309}

, {"className":"org.slf4j.Logger", "importTime":304}

, {"className":"io.netty.buffer.ByteBuf", "importTime":295}

, {"className":"org.slf4j.LoggerFactory", "importTime":292}

, {"className":"com.alibaba.fastjson.serializer.SerializerFeature", "importTime":286}

, {"className":"java.io.OutputStream", "importTime":286}

, {"className":"java.util.Locale", "importTime":285}

, {"className":"javax.servlet.http.HttpServletResponse", "importTime":268}

, {"className":"org.eclipse.jetty.util.log.Logger", "importTime":266}

, {"className":"javax.servlet.ServletException", "importTime":259}

, {"className":"javax.servlet.http.HttpServletRequest", "importTime":255}

, {"className":"org.eclipse.jetty.util.log.Log", "importTime":255}

, {"className":"io.netty.channel.ChannelHandlerContext", "importTime":248}

, {"className":"java.util.concurrent.ConcurrentHashMap", "importTime":245}

, {"className":"java.net.URL", "importTime":244}

, {"className":"static org.junit.Assert.assertTrue", "importTime":240}

, {"className":"java.net.InetSocketAddress", "importTime":239}

, {"className":"com.alibaba.dubbo.common.Constants", "importTime":231}

, {"className":"org.apache.juli.logging.Log", "importTime":222}

, {"className":"org.apache.mina.core.session.IoSession", "importTime":218}

....

 

源码:

https://github.com/Slive/org.slive.project.style

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值