獲取指定包中的class和獲取class中的所有註解的值,封裝性很不錯

關注github:https://github.com/zhangpeibisha

目前Java中使用註解來完成一些業務十分方便,因此我們急需一些能夠讀取類信息和獲取類中的指定的註解的詳細信息。

以下是我封裝了的方法:

1.ScanPack 用來掃描指定包中的文件(包括jar、java、class)

package org.nix.book.common.utils.scan;

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.LinkedHashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * Create by [email protected] on 2018/6/3.
 */
public class ScanPack {

    private ScanPack(){

    }

    /**
     * 從包package中獲取所有的Class
     *
     * @param pack 指定掃描的包
     * @return 包裏面的所有文件
     */
    public static Set<Class<?>> getClasses(String pack) {

        // 第一個class類的集合
        Set<Class<?>> classes = new LinkedHashSet<Class<?>>();
        // 是否循環迭代
        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)) {
                    System.err.println("file類型的掃描");
                    // 獲取包的物理路徑
                    String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
                    // 以文件的方式掃描整個包下的文件 並添加到集合中
                    findAndAddClassesInPackageByFile(packageName, filePath,
                            recursive, classes);
                } else if ("jar".equals(protocol)) {
                    // 如果是jar包文件
                    // 定義一個JarFile
                    System.err.println("jar類型的掃描");
                    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
                                            classes.add(Class
                                                    .forName(packageName + '.'
                                                            + className));
                                        } catch (ClassNotFoundException e) {
                                            // log
                                            // .error("添加用戶自定義視圖類錯誤 找不到此類的.class文件");
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }
                        }
                    } catch (IOException e) {
                        // log.error("在掃描用戶定義視圖時從jar包獲取文件出錯");
                        e.printStackTrace();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return classes;
    }

    /**
     * 以文件的形式來獲取包下的所有Class
     *
     * @param packageName 包的名字
     * @param packagePath 包的路徑
     * @param recursive
     * @param classes 文件列表
     */
    public static void findAndAddClassesInPackageByFile(String packageName,
                                                        String packagePath,
                                                        final boolean recursive,
                                                        Set<Class<?>> classes) {
        // 獲取此包的目錄 建立一個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,
                        classes);
            } else {
                // 如果是java類文件 去掉後面的.class 只留下類名
                String className = file.getName().substring(0,
                        file.getName().length() - 6);
                try {
                    // 添加到集合中去
                    //classes.add(Class.forName(packageName + '.' + className));
                    //經過回覆同學的提醒,這裏用forName有一些不好,會觸發static方法,沒有使用classLoader的load乾淨
                    classes.add(Thread.currentThread().getContextClassLoader().loadClass(packageName + '.' + className));
                } catch (ClassNotFoundException e) {
                    // log.error("添加用戶自定義視圖類錯誤 找不到此類的.class文件");
                    e.printStackTrace();
                }
            }
        }
    }


}
2.自定義 KeepAnnotation類來保存註解信息
package org.nix.book.common.utils.scan;

import java.lang.annotation.Annotation;
import java.util.Map;

/**
 * Create by [email protected] on 2018/6/3.
 *
 * 用來保存掃描到的註解集合
 */
public class KeepAnnotation {

    private Class classzz;

    private Annotation classzzAnnotation;

    private Map<String,Annotation> methodAnnotation;

    public KeepAnnotation(Class classzz) {
        this.classzz = classzz;
    }

    public Class getClasszz() {
        return classzz;
    }

    public void setClasszz(Class classzz) {
        this.classzz = classzz;
    }

    public Annotation getClasszzAnnotation() {
        return classzzAnnotation;
    }

    public void setClasszzAnnotation(Annotation classzzAnnotation) {
        this.classzzAnnotation = classzzAnnotation;
    }

    public Map<String, Annotation> getMethodAnnotation() {
        return methodAnnotation;
    }

    public void setMethodAnnotation(Map<String, Annotation> methodAnnotation) {
        this.methodAnnotation = methodAnnotation;
    }

    @Override
    public String toString() {
        return "KeepAnnotation{" +
                "classzz=" + classzz +
                ", classzzAnnotation=" + classzzAnnotation +
                ", methodAnnotation=" + methodAnnotation +
                '}';
    }
}

3. 定義掃描註解工具類 ScanAnnotation

package org.nix.book.common.utils.scan;

import org.nix.book.entity.book.Book;

import javax.persistence.Column;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.*;

/**
 * Create by [email protected] on 2018/6/3.
 * <p>
 * 掃描指定包的註解
 */
public class ScanAnnotation {
    /**
     * 查詢指定包中的類的所有註解
     * @param packagePath 指定包路徑
     * @param annotation 需要查詢的註解
     * @param checkRepeat 是否查重
     * @return 註解集合
     * @throws Exception 如果有兩個方法上的兩個註解完全相同時則拋出異常
     */
    public static List<KeepAnnotation> getAnnotationByPackage(String packagePath
            , Class<? extends Annotation> annotation
            , boolean checkRepeat) throws Exception {

        Set<Class<?>> classes = ScanPack.getClasses(packagePath);
        List<KeepAnnotation> keepAnnotations = new ArrayList<>(classes.size());

        for (Class classzz : classes) {
            KeepAnnotation keepAnnotation = getAnnotationByClass(classzz, annotation, checkRepeat);
            keepAnnotations.add(keepAnnotation);
        }
        return keepAnnotations;
    }

    /**
     * 查找一個類上的所有註解
     *
     * @param classzz     指定查找的類
     * @param annotation  需要獲取的註解
     * @param checkRepeat 是否查找重複的註解
     * @return 註解集合
     * @throws Exception 如果有兩個方法上的兩個註解完全相同時則拋出異常
     */
    public static KeepAnnotation getAnnotationByClass(Class<?> classzz
            , Class<? extends Annotation> annotation
            , boolean checkRepeat) throws Exception {

        KeepAnnotation KeepAnnotation = new KeepAnnotation(classzz);

        // 獲取到類上的註解
        Annotation classzzAnnotation = classzz.getAnnotation(annotation);
        if (classzzAnnotation != null) KeepAnnotation.setClasszzAnnotation(classzzAnnotation);

        // 獲取到方法上的註解
        Map<String,Annotation> methodAnnotations = new HashMap<>();
        Method[] methods = classzz.getMethods();
        for (Method method : methods) {
            Annotation methodAnnotation = method.getAnnotation(annotation);
            if (methodAnnotation != null) {
                // 如果需要檢查重複則檢查否則不檢測註解值是否重複
                if (checkRepeat && methodAnnotations.containsValue(methodAnnotation))
                    throw new Exception(classzz.getName() + " \n" + method.getName() + " \n"
                            + methodAnnotation.toString() + " have repeat value");
                else {
                    methodAnnotations.put(method.getName(),methodAnnotation);
                }

            }
        }
        KeepAnnotation.setMethodAnnotation(methodAnnotations);
        return KeepAnnotation;
    }


    public static void main(String[] args) throws Exception {
//        Set<Class<?>> classes = ScanPack.getClasses("");
        KeepAnnotation KeepAnnotation = getAnnotationByClass(Book.class, Column.class, false);
        System.out.println();
    }
}

Over,現在可以完成自己需要使用註解來實現的具體功能了。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章