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
| package fr.developpez.dynapipoc;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import javax.swing.JOptionPane;
public class InitClassLoader {
private static final String PARAMETER_USE_FILE = "useFile";
private static final String APINATIVE = "apinative.jar";
private static final String API = "api.jar";
private static final String PACKAGE = Main.class.getPackage().getName().replace('.', '/') + "/lib/";
private static final String APINATIVEJAR = PACKAGE + APINATIVE;
private static final String APIJAR = PACKAGE + API;
public static void init() {
switch (JOptionPane.showOptionDialog(null, "Choose API", "POC",
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
null, new Object[] { "Native", "Not native", "Exit" }, 0)) {
case JOptionPane.YES_OPTION:
loadNativeApi();
break;
case JOptionPane.NO_OPTION:
loadNotNativeApi();
break;
default:
System.err.println("Exit");
System.exit(-1);
}
}
private static void loadNativeApi() {
if ( useFile() ) {
addFile(APINATIVE);
}
else {
loadAPI(APINATIVEJAR);
}
}
private static void loadNotNativeApi() {
if ( useFile() ) {
addFile(API);
}
else {
loadAPI(APIJAR);
}
}
private static boolean useFile() {
return Boolean.getBoolean(PARAMETER_USE_FILE);
}
private static void loadAPI(String jar) {
final URL url = Main.class.getClassLoader().getResource(jar);
addURL(url);
}
private static final Class<?>[] PARAMETERS = new Class[]{URL.class};
public static void addFile(String s) {
File f = new File(s);
addFile(f);
}
public static void addFile(File f) {
try {
addURL(f.toURI().toURL());
} catch (MalformedURLException e) {
e.printStackTrace();
System.exit(-1);
}
}
public static void addURL(URL url) {
URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
URL urls[] = sysLoader.getURLs();
for (int i = 0; i < urls.length; i++) {
if (urls[i].toString().equalsIgnoreCase(url.toString())) {
System.err.println("URL " + url + " is already in the CLASSPATH");
return;
}
}
Class<?> sysclass = URLClassLoader.class;
try {
Method method = sysclass.getDeclaredMethod("addURL", PARAMETERS);
method.setAccessible(true);
System.out.println("Add url "+ url);
method.invoke(sysLoader, new Object[] { url });
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
System.err.println("Error, could not add URL to system classloader");
System.exit(-1);
}
}
} |
Partager