Como usar una libreria que no esta en el classpath


package org.wso2.carbon.classloading;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

public class Main {
    public static void main(String[] args) throws ClassNotFoundException, MalformedURLException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{new URL("file:///home/shameera/Desktop/gson-2.2.4.jar")});
        Class gsonClass = urlClassLoader.loadClass("com.google.gson.Gson");
        Constructor constructor = gsonClass.getConstructor();
        Object gsonObj = constructor.newInstance();
        Method method = gsonClass.getMethod("toJson",Object.class);
        Object returnObj =  method.invoke(gsonObj, new Person());
        String jsonString = (String)returnObj;
        System.out.println(jsonString);
    }
}

Visto en….

Anuncios
Como usar una libreria que no esta en el classpath