简体   繁体   English

使用自定义ClassLoader加载类而不使用String

[英]Loading a class with custom ClassLoader without using a String

I have created a custom ClassLoader and want to load a class. 我创建了一个自定义的ClassLoader,并希望加载一个类。 I am using this code at the moment to load the class from the Jar: 我现在正在使用此代码从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. 在上面的示例中,您可以清楚地看到我正在尝试加载Main类。 Now imagine that my friend also creates a Jar, I cannot know on beforehand what the name of the class is. 现在想象一下,我的朋友也创建了一个Jar,我事先无法知道类的名称。 How can I avoid the usage of a String as argument? 如何避免将String用作参数?

You might want to have a look at the ServiceLoader API . 您可能需要看一下ServiceLoader API You can define a common interface for service implementations (classes) that you don't know a priori . 您可以为您不知道先验的服务实现(类)定义一个通用接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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