集册 Java实例教程 查找递归的类名

查找递归的类名

欢马劈雪     最近更新时间:2020-01-02 10:19:05

527
查找递归的类名

/**

 * This class is modified from m-m-m reflection util project, whose website is:

 * http://m-m-m.sourceforge.net/maven/mmm-util/mmm-util-reflect/

 * 

 * Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0

 * http://www.apache.org/licenses/LICENSE-2.0

 *///from nowjava.com

//package com.nowjava;

import java.io.File;


import java.util.Set;


public class Main {

    private static void findClassNamesRecursive(File pkgDir,

            Set<Class<?>> result, StringBuilder qualifiedNameBuilder,

            int qualifiedNamePrefixLength) throws ClassNotFoundException {

        for (File childFile : pkgDir.listFiles()) {

            String fileName = childFile.getName();

            if (childFile.isDirectory()) {

                qualifiedNameBuilder.setLength(qualifiedNamePrefixLength);

                StringBuilder subBuilder = new StringBuilder(

                        qualifiedNameBuilder);
                        /*
                        时   代    Java - nowjava.com 提 供
                        */

                subBuilder.append(fileName);

                subBuilder.append('.');

                findClassNamesRecursive(childFile, result, subBuilder,

                        subBuilder.length());

            } else {

                String simpleClassName = fixClassName(fileName);

                if (simpleClassName != null) {

                    qualifiedNameBuilder

                            .setLength(qualifiedNamePrefixLength);

                    qualifiedNameBuilder.append(simpleClassName);

                    Class<?> clazz = Class.forName(qualifiedNameBuilder

                            .toString());

                    if (!clazz.isInterface() && !clazz.isAnnotation()) {

                        result.add(clazz);

                    }

                }

            }

        }

    }


    private static String fixClassName(String fileName) {

        if (fileName.endsWith(".class")) {

            // remove extension (".class".length() == 6)

            String nameWithoutExtension = fileName.substring(0,

                    fileName.length() - 6);

            // handle inner classes...

            
展开阅读全文