Java Class Find getClassesDir(Class classWithinDir)

Here you can find the source of getClassesDir(Class classWithinDir)

Description

get Classes Dir

License

Open Source License

Declaration

public static File getClassesDir(Class<?> classWithinDir) 

Method Source Code


//package com.java2s;
import java.io.File;

import java.net.URISyntaxException;

public class Main {
    public static File getClassesDir(Class<?> classWithinDir) {
        return getClassesDir(classWithinDir == null ? null : classWithinDir.getName());
    }//from   w  w  w.ja va2s  .  c o  m

    public static File getClassesDir(String classWithinDir) {
        String clazzResourceName = getResourceNameOfClass(classWithinDir) + ".class";
        File classFile;

        try {
            classFile = new File(
                    Thread.currentThread().getContextClassLoader().getResource(clazzResourceName).toURI());
        } catch (URISyntaxException e) {
            throw new RuntimeException("Could not find classes dir of " + classWithinDir, e);
        }

        File classesdir = classFile.getParentFile();

        for (; classesdir != null && classesdir.isDirectory(); classesdir = classesdir.getParentFile()) {
            if (new File(classesdir, clazzResourceName).equals(classFile)) {
                break;
            }
        }

        if (!classFile.equals(new File(classesdir, clazzResourceName))) {
            throw new RuntimeException("Could not find classes dir of " + classWithinDir);
        }

        return classesdir;
    }

    private static String getResourceNameOfClass(String className) {
        if (className == null) {
            return null;
        }

        return className.trim().replace('.', '/');
    }
}

Related

  1. getClasses(final String packageName, final Class annotation)
  2. getClasses(final String pckgname)
  3. getClasses(String pack)
  4. getClasses(String pkgname, boolean flat)
  5. getClassesAsList(String pckgname, Class type)
  6. getClassesExtending(Class rootClass, String pattern)
  7. getClassesInDirectory(File directory, String packageName, ClassLoader classLoader)
  8. getClassesLocation(Class cls)
  9. getClassesWithInterface(String packageName, Class interfaceClazz)