简体   繁体   中英

Loading a class with custom ClassLoader without using a String

I have created a custom ClassLoader and want to load a class. I am using this code at the moment to load the class from the Jar:

    ByteArrayInputStream byteIS = new ByteArrayInputStream(data);
    JarInputStream jarIS = new JarInputStream(byteIS);
    JarEntry je;
    je = jarIS.getNextJarEntry();
    byte[] classbytes = new byte[(int) je.getSize()];
    jarIS.read(classbytes, 0, classbytes.length);
    jarIS.close();
    CustomClassLoader classLoader = new CustomClassLoader();
    classLoader.setClassContent(classbytes);
    Class c = classLoader.findClass("Main");
    Object object = c.newInstance();
    Method[] methods = object.getClass().getMethods();
    Object returnValue = methods[0].invoke(null, new Object[]{new String[]{}});

In this sample above you can clearly see I am trying to load class Main. Now imagine that my friend also creates a Jar, I cannot know on beforehand what the name of the class is. How can I avoid the usage of a String as argument?

You might want to have a look at the ServiceLoader API . You can define a common interface for service implementations (classes) that you don't know a priori .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM