Search code examples
javadynamicimportpackageclassloader

Dynamic import programmatically


I simply want to implement that line programmatically in runtime.

import com.company.package.*;

I can't believe all the searches lead to Python, and I certainly would prefer not loading classes and looping one by one. It must be a faster command.

Any suggestion?

P.S: I know it's not the best of designs, but I am doing it through a JSP, so perhaps there is some way to use a parameter in the declaration as in

<%@ page import=%{myPackage} %>


Solution

  • ClassLoader is too dynamic/flexible to do what you're asking. Specifically, there is no portable way to list the contents of a directory from a ClassLoader, so there is no way to determine the complete set of classes to be loaded. Here are two non-portable suggestions:

    1. Assume your ClassLoader implements URLClassLoader, then call getURLs, then assume the URLs are file: ...or:
    2. Assume ClassLoader.getResource("com/company/package/") will return a non-null URL, then assume the URL will be file: (or jar:, then assume the inner URL is file:, and then extract and use that)

    In either case, parse file: URL (handling URL decoding), list the contents of the directory/JAR to find all *.class files.

    Note, this is basically what Spring classpath*: does, and they include several portability warnings in their documentation for these reasons.