org.msec.rpc.ClassUtils.java Source code

Java tutorial

Introduction

Here is the source code for org.msec.rpc.ClassUtils.java

Source

/**
 * Tencent is pleased to support the open source community by making MSEC available.
 *
 * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
 *
 * Licensed under the GNU General Public License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. You may 
 * obtain a copy of the License at
 *
 *     https://opensource.org/licenses/GPL-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the 
 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language governing permissions
 * and limitations under the License.
 */

package org.msec.rpc;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class ClassUtils {

    public static Class loadClass(ClassLoader classLoader, String className) throws ClassNotFoundException {
        if (classLoader == null) {
            classLoader = Thread.currentThread().getContextClassLoader();
        }
        return org.apache.commons.lang.ClassUtils.getClass(classLoader, className);
    }

    public static Class loadClass(String className) throws ClassNotFoundException {
        return loadClass(null, className);
    }

    public static ClassLoader getCurrentClassLoader(ClassLoader classLoader) {
        if (classLoader != null) {
            return classLoader;
        }
        ClassLoader currentLoader = Thread.currentThread().getContextClassLoader();
        if (currentLoader != null) {
            return currentLoader;
        }
        return ClassUtils.class.getClassLoader();
    }

    /**
     * package?Class
     * 
     * @param pack
     * @return
     */
    public static void loadClasses(String pack) {
        // ?
        boolean recursive = true;
        // ??? ?
        String packageName = pack;
        String packageDirName = packageName.replace('.', '/');
        // ? ??things
        Enumeration<URL> dirs;
        try {
            dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
            // 
            while (dirs.hasMoreElements()) {
                // ?
                URL url = dirs.nextElement();
                // ????
                String protocol = url.getProtocol();
                // ???
                if ("file".equals(protocol)) {
                    // ??
                    String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
                    // ??? ?
                    findAndAddClassesInPackageByFile(packageName, filePath, recursive);
                } else if ("jar".equals(protocol)) {
                    // jar
                    // JarFile
                    JarFile jar;
                    try {
                        // ?jar
                        jar = ((JarURLConnection) url.openConnection()).getJarFile();
                        // jar 
                        Enumeration<JarEntry> entries = jar.entries();
                        // ?
                        while (entries.hasMoreElements()) {
                            // ?jar ? jar META-INF
                            JarEntry entry = entries.nextElement();
                            String name = entry.getName();
                            // /
                            if (name.charAt(0) == '/') {
                                // ???
                                name = name.substring(1);
                            }
                            // ?????
                            if (name.startsWith(packageDirName)) {
                                int idx = name.lastIndexOf('/');
                                // "/" 
                                if (idx != -1) {
                                    // ??? "/"??"."
                                    packageName = name.substring(0, idx).replace('/', '.');
                                }
                                // ? 
                                if ((idx != -1) || recursive) {
                                    // .class ?
                                    if (name.endsWith(".class") && !entry.isDirectory()) {
                                        // ??".class" ???
                                        String className = name.substring(packageName.length() + 1,
                                                name.length() - 6);
                                        try {
                                            // classes
                                            Class.forName(packageName + '.' + className);
                                        } catch (ClassNotFoundException e) {
                                            // log
                                            // .error(" ?.class");
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }
                        }
                    } catch (IOException e) {
                        // log.error("??jar?");
                        e.printStackTrace();
                    }
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    /**
     * ???Class
     * 
     * @param packageName
     * @param packagePath
     * @param recursive
     * @param classes
     */
    public static void findAndAddClassesInPackageByFile(String packageName, String packagePath,
            final boolean recursive) {
        // ? File
        File dir = new File(packagePath);
        // ? ?
        if (!dir.exists() || !dir.isDirectory()) {
            // log.warn("?? " + packageName + " ");
            return;
        }
        //  ? 
        File[] dirfiles = dir.listFiles(new FileFilter() {
            //  ?(??) .class(java)
            public boolean accept(File file) {
                return (recursive && file.isDirectory()) || (file.getName().endsWith(".class"));
            }
        });
        // 
        for (File file : dirfiles) {
            //  ??
            if (file.isDirectory()) {
                findAndAddClassesInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(),
                        recursive);
            } else {
                // java ??.class ???
                String className = file.getName().substring(0, file.getName().length() - 6);
                try {
                    Class.forName(packageName + '.' + className);
                    // classes.add(Thread.currentThread().getContextClassLoader().loadClass(packageName
                    // + '.' + className));
                } catch (ClassNotFoundException e) {
                    // log.error(" ?.class");
                    e.printStackTrace();
                }
            }
        }
    }
}