悠然乱弹:从几个方法的重构讲开去--引言

  1. 云栖社区>
  2. 博客>
  3. 正文

悠然乱弹:从几个方法的重构讲开去--引言

悠悠悠然然 2016-05-09 14:01:45 浏览1409
展开阅读全文

引言:

在学习代码的过程中,看到如下几个工具方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// 获取指定包名下的所有类
    public static List<Class<?>> getClassList(String packageName, boolean isRecursive) {
        List<Class<?>> classList = new ArrayList<Class<?>>();
        try {
            Enumeration<URL> urls = getClassLoader().getResources(packageName.replace(".", "/"));
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                if (url != null) {
                    String protocol = url.getProtocol();
                    if (protocol.equals("file")) {
                        String packagePath = url.getPath();
                        addClass(classList, packagePath, packageName, isRecursive);
                    } else if (protocol.equals("jar")) {
                        JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
                        JarFile jarFile = jarURLConnection.getJarFile();
                        Enumeration<JarEntry> jarEntries = jarFile.entries();
                        while (jarEntries.hasMoreElements()) {
                            JarEntry jarEntry = jarEntries.nextElement();
                            String jarEntryName = jarEntry.getName();
                            if (jarEntryName.endsWith(".class")) {
                                String className = jarEntryName.substring(0, jarEntryName.lastIndexOf(".")).replaceAll("/", ".");
                                if (isRecursive || className.substring(0, className.lastIndexOf(".")).equals(packageName)) {
                                    classList.add(loadClass(className, false));
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("获取类出错!", e);
            throw new RuntimeException(e);
        }
        return classList;
    }
 
    // 获取指定包名下指定注解的所有类
    public static List<Class<?>> getClassListByAnnotation(String packageName, Class<? extends Annotation> annotationClass) {
        List<Class<?>> classList = new ArrayList<Class<?>>();
        try {
            Enumeration<URL> urls = getClassLoader().getResources(packageName.replace(".", "/"));
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                if (url != null) {
                    String protocol = url.getProtocol();
                    if (protocol.equals("file")) {
                        String packagePath = url.getPath();
                        addClassByAnnotation(classList, packagePath, packageName, annotationClass);
                    } else if (protocol.equals("jar")) {
                        JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
                        JarFile jarFile = jarURLConnection.getJarFile();
                        Enumeration<JarEntry> jarEntries = jarFile.entries();
                        while (jarEntries.hasMoreElements()) {
                            JarEntry jarEntry = jarEntries.nextElement();
                            String jarEntryName = jarEntry.getName();
                            if (jarEntryName.endsWith(".class")) {
                                String className = jarEntryName.substring(0, jarEntryName.lastIndexOf(".")).replaceAll("/", ".");
                                Class<?> cls = loadClass(className, false);
                                if (cls.isAnnotationPresent(annotationClass)) {
                                    classList.add(cls);
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("获取类出错!", e);
            throw new RuntimeException(e);
        }
        return classList;
    }
 
    // 获取指定包名下指定父类的所有类
    public static List<Class<?>> getClassListBySuper(String packageName, Class<?> superClass) {
        List<Class<?>> classList = new ArrayList<Class<?>>();
        try {
            Enumeration<URL> urls = getClassLoader().getResources(packageName.replace(".", "/"));
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                if (url != null) {
                    String protocol = url.getProtocol();
                    if (protocol.equals("file")) {
                        String packagePath = url.getPath();
                        addClassBySuper(classList, packagePath, packageName, superClass);
                    } else if (protocol.equals("jar")) {
                        JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
                        JarFile jarFile = jarURLConnection.getJarFile();
                        Enumeration<JarEntry> jarEntries = jarFile.entries();
                        while (jarEntries.hasMoreElements()) {
                            JarEntry jarEntry = jarEntries.nextElement();
                            String jarEntryName = jarEntry.getName();
                            if (jarEntryName.endsWith(".class")) {
                                String className = jarEntryName.substring(0, jarEntryName.lastIndexOf(".")).replaceAll("/", ".");
                                Class<?> cls = loadClass(className, false);
                                if (superClass.isAssignableFrom(cls) && !superClass.equals(cls)) {
                                    classList.add(cls);
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("获取类出错!", e);
            throw new RuntimeException(e);
        }
        return classList;
    }

第一感觉,觉得这几个方法肯定有问题,但是问题在哪里呢?

首先看直接看到的问题:

  • 代码重复得比较多
  • 代码圈复杂度比较大
  • 异常处理模式不能说错,但是是否合理值得商榷

代码重复得比较多,是大家一眼就可以看得到的,但是怎么改?确实也是狗咬刺猬无从下口。
代码圈复杂度,用来标示一个代码的复杂程度,不知道概念的话,问下度娘就知道了。
异常处理模式确实不能算错,也就是说只要有一个类出错,就导致整个处理中断。但是我个人对于处理Class,注解什么的,比较倾向于有错记下来,但是不要影响别的类的处理的模式。只能说两种模式各有优缺点,因此可以商榷。

再来分析下深层次方面的问题

  • 性能问题
  • 扩展问题

说到性能问题,我们都知道,应用大到一定程度的时候,Jar文件,类文件都是比较多的,如果每处理一个注解之类的就扫描一次,就会化大量的时候在重复的目录(JarEntry)遍历上;我在合计20M的Jar里遍历所有的class文件,在本人笔记本上大概是2S时间,如果注解多了,那可是一个注解2秒的时间呀。

说到扩展问题,现在我们处理的都是Jar文件,那当然可能有本地文件,也可能有URL外部的文件,还可能有自已写的ClassLoader加载的其它文件,上面的处理无疑只能处理前面两种,如果是自己写的ClassLoader肯定是不在扫描之列了。另外,现在处理的是class文件,当然也可能处理的是一些xml文件或国际化文件等等。这样子一来,这里的工具方法岂不是要爆炸式增长??

当然,写此代码作者决非一般人等,如果简单,他不会让它留着的。

因此,在这短短的几个方法里都就隐藏着怎样的秘密呢?,

网友评论

登录后评论
0/500
评论
悠悠悠然然
+ 关注