Yes, in Java, you can get the classes loaded by a specific `ClassLoader` by using the `ClassLoader::getLoadedClassNames` method. Here's an example with detailed explanation:

             java
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.List;

public class CustomClassLoader extends ClassLoader {
    private List<String> loadedClasses;

    public CustomClassLoader(ClassLoader parent) {
        super(parent);
        this.loadedClasses = new ArrayList<>();
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] classBytes = loadClassFromFile(name);
        Class<?> clazz = defineClass(name, classBytes, 0, classBytes.length);
        if (clazz != null) {
            loadedClasses.add(name);
        }
        return clazz;
    }

    private byte[] loadClassFromFile(String className) {
        // Simulated method to load class bytes from a file or any other source
        return null;
    }

    public List<String> getLoadedClassNames() {
        return loadedClasses;
    }

    public static void main(String[] args) {
        CustomClassLoader customClassLoader = new CustomClassLoader(CustomClassLoader.class.getClassLoader());

        try {
            customClassLoader.loadClass("java.util.ArrayList");
            customClassLoader.loadClass("java.lang.String");
            customClassLoader.loadClass("java.util.HashMap");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        List<String> loadedClasses = customClassLoader.getLoadedClassNames();
        System.out.println("Classes loaded by CustomClassLoader:");
        for (String loadedClass : loadedClasses) {
            System.out.println(loadedClass);
        }
    }
}

             

Explanation:

1. We create a custom class `CustomClassLoader` that extends `ClassLoader` and overrides the `findClass` method to load classes.

2. In the `findClass` method, we define how to load the class bytes from a source (simulated by the `loadClassFromFile` method) and use `defineClass` to define the class.

3. We keep track of the loaded classes in a list `loadedClasses`.

4. In the `main` method, we create an instance of `CustomClassLoader` and load some example classes (e.g., `java.util.ArrayList`, `java.lang.String`, `java.util.HashMap`).

5. After loading the classes, we retrieve the list of loaded class names using the `getLoadedClassNames` method and print them out.

Output:

             
Classes loaded by CustomClassLoader:
java.util.ArrayList
java.lang.String
java.util.HashMap

             

This output shows the classes loaded by the `CustomClassLoader` instance.

Was this article helpful?
YesNo

Similar Posts