类操作工具类

package hjp.smart4j.framework.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileFilter;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * 类操作工具类
 */
public final class ClassUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(ClassUtil.class);

    /**
     * 获取类加载器
     */
    public static ClassLoader getClassLoader() {
        return Thread.currentThread().getContextClassLoader();
    }

    /**
     * 加载类
     * className为类的全包名
     */
    public static Class<?> loadClass(String className, boolean isInitialized) {
        Class<?> cls;
        try {
            cls = Class.forName(className, isInitialized, getClassLoader());
        } catch (ClassNotFoundException e) {
            LOGGER.error("load class failure", e);
            throw new RuntimeException();
        }
        return cls;
    }

    /**
     * 获取指定包名下的所有类
     */
    public static Set<Class<?>> getClassSet(String packageName) {
        Set<Class<?>> classSet = new HashSet<Class<?>>();
        try {
            Enumeration<URL> urls = getClassLoader().getResources(packageName.replace(".", "/"));
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                if (url != null) {
                    String protocol = url.getProtocol();//url协议
                    if (protocol.equals("file")) {
                        String packagePath = url.getPath().replaceAll("%20", " ");
                        addClass(classSet, packagePath, packageName);
                    } else if (protocol.equals("jar")) {
                        JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
                        if (jarURLConnection != null) {
                            JarFile jarFile = jarURLConnection.getJarFile();
                            if (jarFile != null) {
                                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("/", ".");
                                        doAddClass(classSet, className);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("get class set failure", e);
            throw new RuntimeException(e);
        }
        return classSet;
    }

    private static void addClass(Set<Class<?>> classSet, String packagePath, String packageName) {
        final File[] files = new File(packagePath).listFiles(new FileFilter() {
            public boolean accept(File file) {
                //过滤出Class文件或文件夹
                return (file.isFile() && file.getName().endsWith(".class")) || file.isDirectory();
            }
        });
        for (File file : files) {
            String fileName = file.getName();
            if (file.isFile()) {
                //如果是类文件构造类文件全包名
                String className = fileName.substring(0, fileName.lastIndexOf("."));
                if (StringUtil.isNotEmpty(packageName)) {
                    className = packageName + "." + className;
                }
                doAddClass(classSet, className);//这个方法就是用Class.forName方法得到类,加到classSet集合中
            } else {
                //如果是文件夹
                //构造此文件夹相对路径
                String subPacakgePath = fileName;
                if (StringUtil.isNotEmpty(subPacakgePath)) {
                    subPacakgePath = packagePath + "/" + subPacakgePath;
                }
                //构造此文件夹包名路径
                String subPacakgeName = fileName;
                if (StringUtil.isNotEmpty(subPacakgeName)) {
                    subPacakgeName = packageName + "." + subPacakgeName;
                }
                //递归加载类
                addClass(classSet, subPacakgePath, subPacakgeName);
            }
        }
    }

    private static void doAddClass(Set<Class<?>> classSet, String className) {
        Class<?> cls = loadClass(className, false);
        classSet.add(cls);
    }

}
时间: 2024-08-05 17:11:36

类操作工具类的相关文章

FileUtils.java 本地 文件操作工具类

package Http; import java.io.File;import java.io.FileOutputStream;import java.io.FileWriter;import java.io.IOException; /** * * 本地文件操作工具类 *保存文本 *保存图片 * Created by lxj-pc on 2017/6/27. */public class FileUtils { public static void saveText(String cont

Code片段 : .properties属性文件操作工具类 &amp; JSON工具类

摘要: 原创出处:www.bysocket.com 泥瓦匠BYSocket 希望转载,保留摘要,谢谢! “贵专” — 泥瓦匠 一.java.util.Properties API & 案例 java.util.Properties 是一个属性集合.常见的api有如下: load(InputStream inStream)  从输入流中读取属性 getProperty(String key)  根据key,获取属性值 getOrDefault(Object key, V defaultValue)

[转载]C# FTP操作工具类

本文转载自<C# Ftp操作工具类>,仅对原文格式进行了整理. 介绍了几种FTP操作的函数,供后期编程时查阅. 参考一: using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Net; using System.Globalization; namespace FtpTest1 { public class FtpWeb { string ftpServe

Java IO(文件操作工具类)

FileOperate实现的功能: 1. 返回文件夹中所有文件列表 2. 读取文本文件内容 3. 新建目录 4. 新建多级目录 5. 新建文件 6. 有编码方式的创建文件 7. 删除文件 8. 删除指定文件夹下所有文件 9. 复制单个文件 10. 复制整个文件夹的内容 11. 移动文件 12. 移动目录 13. 建立一个可以追加的bufferedwriter 14. 得到一个bufferedreader Java代码    package utils; import java.io.Buffer

Android工具类之日期操作工具类

/** * 日期操作工具类. */ public class DateUtil { /** * 英文简写如:2016 */ public static String FORMAT_Y = "yyyy"; /** * 英文简写如:12:01 */ public static String FORMAT_HM = "HH:mm"; /** * 英文简写如:1-12 12:01 */ public static String FORMAT_MDHM = "MM-

反射操作工具类

using System; using System.Collections.Generic; using System.Data; using System.Reflection; namespace Framework.Utility { /// <summary> /// 反射操作工具类 /// </summary> public class ReflectionUtil { #region 根据反射机制将dataTable中指定行的数据赋给obj对象 /// <sum

Android设备内存和SD卡操作工具类

package cc.c; import java.io.File; import java.util.List; import android.os.StatFs; import java.io.FileReader; import java.io.IOException; import java.io.BufferedReader; import android.os.Environment; import android.content.Context; import android.ap

文件操作工具类

package utils; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.Outpu

拼音操作工具类 - PinyinUtil.java

拼音操作工具类,提供字符串转换成拼音数组.汉字转换成拼音.取汉字的首字母等方法. 源码如下:(点击下载 -PinyinUtil.java.pinyin4j-2.5.0.jar ) 1 import net.sourceforge.pinyin4j.PinyinHelper; 2 import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType; 3 import net.sourceforge.pinyin4j.format.HanyuPiny