find Class Names Recursive - Java Reflection

Java examples for Reflection:Class Name

Description

find Class Names Recursive

Demo Code

/**//from  ww w. j ava  2  s  .  com
 * 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
 */
//package com.java2s;
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);
                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...
            /*
             * int lastDollar = nameWithoutExtension.lastIndexOf('$');
             * if (lastDollar > 0) {
             *     char innerClassStart = nameWithoutExtension.charAt(lastDollar + 1);
             *     if ((innerClassStart >= '0') && (innerClassStart <= '9')) {
             *         // ignore anonymous class
             *     }
             *     else {
             *         return nameWithoutExtension.replace('$', '.');
             *     }
             * }
             * else {
             *     return nameWithoutExtension;
             * }
             */
            return nameWithoutExtension;
        }
        return null;
    }
}

Related Tutorials