aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/moe/nea/modernjava/launch/util/ClassLoaderManipulations.java
blob: 6cc21e98aa076a83936e897f060bb76230f1a017 (plain)
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
package moe.nea.modernjava.launch.util;

import net.minecraft.launchwrapper.Launch;
import net.minecraft.launchwrapper.LaunchClassLoader;

import java.io.File;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;

public class ClassLoaderManipulations {
    /**
     * Adds a File to the parent class loader of the launch class loader. Necessary if you want to/have to use
     * {@link LaunchClassLoader#addClassLoaderExclusion(String)}.
     */
    public static void addToParentClassLoader(File file) {
        try {
            addToParentClassLoader(file.toURI().toURL());
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Adds a URL to the parent class loader of the launch class loader. Necessary if you want to/have to use
     * {@link LaunchClassLoader#addClassLoaderExclusion(String)}.
     */
    public static void addToParentClassLoader(URL file) {
        try {
            Launch.classLoader.addURL(file);
            ClassLoader parentClassLoader = Launch.classLoader.getClass().getClassLoader();
            Method addUrl = parentClassLoader.getClass().getDeclaredMethod("addURL", URL.class);
            addUrl.setAccessible(true);
            addUrl.invoke(parentClassLoader, file);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}