簡體   English   中英

使用自定義ClassLoader加載類而不使用String

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

我創建了一個自定義的ClassLoader,並希望加載一個類。 我現在正在使用此代碼從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[]{}});

在上面的示例中,您可以清楚地看到我正在嘗試加載Main類。 現在想象一下,我的朋友也創建了一個Jar,我事先無法知道類的名稱。 如何避免將String用作參數?

您可能需要看一下ServiceLoader API 您可以為您不知道先驗的服務實現(類)定義一個通用接口。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM