powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / Java [игнор отключен] [закрыт для гостей] / Загрузка ресурсов custom-ным classloader-ом
7 сообщений из 7, страница 1 из 1
Загрузка ресурсов custom-ным classloader-ом
    #38137686
aby_2503
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Возникла необходимость загружать классы динамически собственным загрузчиком. Как правильно организовать загрузку ресурсов? Внутри загружаемого класса есть строки типа
Код: java
1.
2.
URL location = Plugin.class.getResource("view/View.fxml");
InputStream stream = location.openStream();


Так вот stream при обращении выбрасывает NullPointerException Загрузку следует производить из jar-ников. На каком-то форуме нашел, что следует переопределить findResource и findResources. Но оно все равно не работает.Ниже представлен код загрузчика
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
189.
190.
191.
192.
193.
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
207.
208.
209.
210.
211.
212.
213.
214.
215.
216.
217.
218.
public class MyClassLoader extends ClassLoader {
    /**
     * scanned class path
     */
    private Vector fPathItems;
    /**
     * default excluded paths
     */
    private String[] defaultExclusions = {
            "java.",
            "javax.",
    };
    /**
     * name of excluded properties file
     */
    static final String EXCLUDED_FILE = "excluded.properties";
    /**
     * excluded paths
     */
    private Vector fExcluded;


    public MyClassLoader() {
        this(System.getProperty("java.class.path"));
    }


    public MyClassLoader(String classPath) {
        super();
        scanPath(classPath);
        readExcludedPackages();
    }

    private void scanPath(String classPath) {
        String separator = System.getProperty("path.separator");
        fPathItems = new Vector(10);
        StringTokenizer st = new StringTokenizer(classPath, separator);
        while (st.hasMoreTokens()) {
            fPathItems.addElement(st.nextToken());
        }
    }

    public URL getResource(String name) {
        return ClassLoader.getSystemResource(name);
    }

    public InputStream getResourceAsStream(String name) {
        return ClassLoader.getSystemResourceAsStream(name);
    }

    public boolean isExcluded(String name) {
        for (int i = 0; i < fExcluded.size(); i++) {
            if (name.startsWith((String) fExcluded.elementAt(i))) {
                return true;
            }
        }
        return false;
    }

    public synchronized Class loadClass(String name, boolean resolve)
            throws ClassNotFoundException {

        Class c = findLoadedClass(name);
        if (c != null)
            return c;
        //
        // Delegate the loading of excluded classes to the
        // standard class loader.
        //
        if (isExcluded(name)) {
            try {
                c = findSystemClass(name);
                return c;
            } catch (ClassNotFoundException e) {
                // keep searching
            }
        }
        if (c == null) {
            byte[] data = lookupClassData(name);
            if (data == null)
                throw new ClassNotFoundException();
            c = defineClass(name, data, 0, data.length);
        }
        if (resolve)
            resolveClass(c);
        return c;
    }

    private byte[] lookupClassData(String className) throws ClassNotFoundException {
        byte[] data = null;
        for (int i = 0; i < fPathItems.size(); i++) {
            String path = (String) fPathItems.elementAt(i);
            String fileName = className.replace('.', '/') + ".class";
            if (isJar(path)) {
                data = loadJarData(path, fileName);
            } else {
                data = loadFileData(path, fileName);
            }
            if (data != null)
                return data;
        }
        throw new ClassNotFoundException(className);
    }

    boolean isJar(String pathEntry) {
        return pathEntry.endsWith(".jar") || pathEntry.endsWith(".zip");
    }

    private byte[] loadFileData(String path, String fileName) {
        File file = new File(path, fileName);
        if (file.exists()) {
            return getClassData(file);
        }
        return null;
    }

    private byte[] getClassData(File f) {
        FileInputStream stream = null;
        try {
            stream = new FileInputStream(f);
            ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = stream.read(b)) != -1)
                out.write(b, 0, n);
            stream.close();
            out.close();
            return out.toByteArray();

        } catch (IOException e) {
        } finally {
            if (stream != null)
                try {
                    stream.close();
                } catch (IOException e1) {
                }
        }
        return null;
    }

    private byte[] loadJarData(String path, String fileName) {
        JarFile jarFile = null;
        InputStream stream = null;
        File archive = new File(path);
        if (!archive.exists())
            return null;
        try {
            jarFile = new JarFile(archive);
        } catch (IOException io) {
            return null;
        }
        JarEntry entry = jarFile.getJarEntry(fileName);
        if (entry == null)
            return null;
        int size = (int) entry.getSize();
        try {
            stream = jarFile.getInputStream(entry);
            byte[] data = new byte[size];
            int pos = 0;
            while (pos < size) {
                int n = stream.read(data, pos, data.length - pos);
                pos += n;
            }
            jarFile.close();
            return data;
        } catch (IOException e) {
        } finally {
            try {
                if (stream != null)
                    stream.close();
            } catch (IOException e) {
            }
        }
        return null;
    }

    private void readExcludedPackages() {
        fExcluded = new Vector(10);
        for (int i = 0; i < defaultExclusions.length; i++)
            fExcluded.addElement(defaultExclusions[i]);

        InputStream is = getClass().getResourceAsStream(EXCLUDED_FILE);
        if (is == null)
            return;
        Properties p = new Properties();
        try {
            p.load(is);
        } catch (IOException e) {
            return;
        } finally {
            try {
                is.close();
            } catch (IOException e) {
            }
        }
        for (Enumeration e = p.propertyNames(); e.hasMoreElements(); ) {
            String key = (String) e.nextElement();
            if (key.startsWith("excluded.")) {
                String path = p.getProperty(key);
                path = path.trim();
                if (path.endsWith("*"))
                    path = path.substring(0, path.length() - 1);
                if (path.length() > 0)
                    fExcluded.addElement(path);
            }
        }
    }

    @Override
    protected URL findResource(String name) {        
        return null;
    }

    @Override
    protected Enumeration<URL> findResources(String name) throws IOException {        
        return super.findResources(name);    //To change body of overridden methods use File | Settings | File Templates.
    }
}
...
Рейтинг: 0 / 0
Загрузка ресурсов custom-ным classloader-ом
    #38137693
Фотография Blazkowicz
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Если вы читаете классы из традиционных источников, то и наследоваться стоило от URLClassLoader.
Почему было не взять какой-то простейший фреймверк для плагинов, типа http://jpf.sourceforge.net/
...
Рейтинг: 0 / 0
Загрузка ресурсов custom-ным classloader-ом
    #38137699
Фотография Blazkowicz
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Так же, полагаю, вы забыли передать ссылку на родительский загрузчик. В этом случае классы плагина будут видеть только классы JSE, но не будут видеть классы вашего приложения. Почитайте про иерархию загрузчиков.
...
Рейтинг: 0 / 0
Загрузка ресурсов custom-ным classloader-ом
    #38137840
aby_2503
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Для меня не важна модульность. Загрузчик мне необходим, чтобы перегружать загруженные классы
...
Рейтинг: 0 / 0
Загрузка ресурсов custom-ным classloader-ом
    #38137848
Фотография Blazkowicz
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
aby_2503Для меня не важна модульность. Загрузчик мне необходим, чтобы перегружать загруженные классы
Это к чему именно коментарий? Кто-то выше писал про модульность?
...
Рейтинг: 0 / 0
Загрузка ресурсов custom-ным classloader-ом
    #38137852
aby_2503
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
BlazkowiczЕсли вы читаете классы из традиционных источников, то и наследоваться стоило от URLClassLoader.
Почему было не взять какой-то простейший фреймверк для плагинов, типа http://jpf.sourceforge.net/
...
Рейтинг: 0 / 0
Загрузка ресурсов custom-ным classloader-ом
    #38137859
Фотография Blazkowicz
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
- Если вы читаете классы из традиционных источников, то и наследоваться стоило от URLClassLoader.
- Для меня не важна модульность. Загрузчик мне необходим, чтобы перегружать загруженные классы

Конструктивный разговор получается.
...
Рейтинг: 0 / 0
7 сообщений из 7, страница 1 из 1
Форумы / Java [игнор отключен] [закрыт для гостей] / Загрузка ресурсов custom-ным classloader-ом
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]