All java java class in a package scanning and load

  A recent study notes and java reflection, practical scenarios need to scan all java class in a package, and then use the class loader to load classes.

  The basic idea of ​​the path is obtained for the scanning and the sub-packets java classes in a package under the src, it is relatively simple to achieve.

  Operating environment: windows10 + jdk1.8 + eclipse

  Directly attached to the code

  

Package org.test.scanner; 

Import java.io.File;
 Import of java.util.ArrayList;
 Import java.util.List; 

/ * 
 * DATE: 2019-07-23 
 * * / 
public  class PackageScanner {
     Private List <Class < ? >> classes;
     Private String PackagePath = null ; 

    / * 
     * constructor with no arguments, called internally with reference constructor. 
     * 
     * @Throw ClassNotFound 
     * 
     * / 
    public PackageScanner () throws a ClassNotFoundException {
         the this ( "" ); 
    }

    / * 
     * Realize, fileScanner calls for directory scanning and loading 
     * 
     * @param String to scan incoming packets 
     * 
     * @throw ClassNotFound 
     * / 
    public PackageScanner (String basePackage) throws ClassNotFoundException { 
        PackagePath = System.getProperty ( "user.dir" ) + "\\ src \\" ; 
        String filePath = PackagePath + basePackage.replace (, '\\' '.' ); 
        classes = new new ArrayList <Class <>>? (); 
        FileScanner ( new new File (filePath)) ; 
    } 

    Private  void FileScanner (File File) throws ClassNotFoundException {
        if (file.isFile() && file.getName().lastIndexOf(".java") == file.getName().length() - 5) {//5是".java"的长度
            String filePath = file.getAbsolutePath();
            String qualifiedName = filePath.substring(packagePath.length(), filePath.length() - 5).replace('\\', '.');
            System.out.println(qualifiedName);
            classes.add(Class.forName(qualifiedName));
            return;
        } else if (file.isDirectory()) {
            for (File f : file.listFiles())
                fileScanner(f);
        }
    }

    / * 
     * Get loaded into a List class object, returns the ArrayList 
     * / 
    public List <Class <>>? GetClasses () {
         return  the this .classes; 
    } 
}

  

This package is a simple scanning type, here used as the Class.forName () to load the scan class

We can look to achieve forName

 

public static Class<?> forName(String className) throws ClassNotFoundException {
	return forName0(className, true, ClassLoader.getCallerClassLoader());
	}

 

Found called ClassLoader.getCallerClassLoader () 

As can be seen from the name is to get the class loader calls the class, we can look at its implementation

 

static ClassLoader getCallerClassLoader() {
		// NOTE use of more generic Reflection.getCallerClass()
		Class caller = Reflection.getCallerClass(3);
		// This can be null if the VM is requesting it
		if (caller == null) {
			return null;
		}
		return caller.getClassLoader0();
	}

 

The key one: Reflection.getCallerClass (3).

It has been passed up, until it get to call the class, and then get the class loader calls the class


In which the parameters REflection.getCallerClass () are:

Less than 0 and 0 - Back Reflection Class 

1-- return to their Class 

2 - returns the class of the caller 
3. 4. .... layers upload.

 

The final aim is who call this class, call the class's class loader is responsible for loading the class. Only when it's loaded class is null, that is not available, just use getClassLoader0 () This method any native loader, which is to start implementation class loader, if not java lib directory of the library, the class is not It will be loaded.

 

By learning java package scanning and class loading, I simply know how the java class loader.

Limited capacity, if wrong, please inform soon.

 

 

ps: Learning without thought is labor lost, thought without learning is perilous.

Guess you like

Origin www.cnblogs.com/lingdurebing/p/ldrb-java.html