Search code examples
javaclassloaderinstantiation.class-file

Get instance of the class of a ClassFile


i've a folder which contains jar files. i load all of those files, then i load all of the class files which are in the jar files. now i want to make an instance of every class of the class files.

ClassFile[] classFiles = loadClassFiles();
Object[] objects = new Object[classFiles.length];
for(int i = 0; i < classFiles.length; i++){
 objects[i] = getNewInstanceOf(classfiles[i]);
}

This is what i ve so far. only the method getNewInstaceOf(Classfile file) is missed. Can anyone tell me how to do this?

If there is an easier way to load all classes from a jar file, you can also tell me. i don't have to get the classFiles or to load the jarfile, if there is any other way.

Also you might should know, that every Class does have a constructor without parameters
thanks for help :)


Solution

  • If you know the name of the class you want you could use

    File file = getJarFileToLoadFrom();   
    String lcStr = getNameOfClassToLoad();   
    URL jarfile = new URL("jar", "","file:" + file.getAbsolutePath()+"!/");    
    URLClassLoader cl = URLClassLoader.newInstance(new URL[] {jarfile });   
    Class loadedClass = cl.loadClass(lcStr);