Example usage for java.lang ClassLoader loadClass

List of usage examples for java.lang ClassLoader loadClass

Introduction

In this page you can find the example usage for java.lang ClassLoader loadClass.

Prototype

public Class<?> loadClass(String name) throws ClassNotFoundException 

Source Link

Document

Loads the class with the specified binary name.

Usage

From source file:com.smash.revolance.ui.explorer.Explorer.java

private Application instanciateApplication(File applicationJar, String fullClassName)
        throws ClassNotFoundException, MalformedURLException, NoSuchMethodException, IllegalAccessException,
        InvocationTargetException, InstantiationException {
    ClassLoader loader = new JarClassLoader(applicationJar.toURI().toURL());
    if (loader == null) {
        loader = Thread.currentThread().getContextClassLoader();
    }/*from w ww.  j  a va  2  s .co m*/
    Class<?> applicationClass = loader.loadClass(fullClassName);
    return (Application) applicationClass.getDeclaredConstructor().newInstance();
}

From source file:com.sun.faces.util.Util.java

public static Class loadClass(String name, Object fallbackClass) throws ClassNotFoundException {
    ClassLoader loader = Util.getCurrentLoader(fallbackClass);
    return loader.loadClass(name);
}

From source file:edu.rosehulman.sws.extension.AbstractPlugin.java

private void parseRouteLine(String line) {
    // split line on any amount of white space in between parts
    String[] routeParts = line.split("\\s+");
    String path = routeParts[0].replaceAll(".*[/\\\\].*", File.separator);
    String routeKey = getServeltRouteKey(path, routeParts[1]);
    String routeServletClass = routeParts[2];

    // create new servlet instance frome routeServlet name
    Class<?> servletClass;//  w w  w  .  j  a  v a 2s  . c o m
    try {
        URL location = getClass().getProtectionDomain().getCodeSource().getLocation();
        ClassLoader classLoader = new URLClassLoader(
                new URL[] { new File(location.getFile()).toURI().toURL() });
        servletClass = classLoader.loadClass(routeServletClass);
        Constructor<?> servletConstructor = servletClass.getConstructor();
        Object servletObj = servletConstructor.newInstance();
        IServlet servlet = (IServlet) servletObj;
        servlet.setPlugin(this);
        this.servletMap.put(routeKey, servlet);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:py.una.pol.karaku.replication.client.ReplicationLogic.java

@SuppressWarnings("unchecked")
private ReplicationInfo loadClass(ReplicationInfo ri) {

    try {// w w w.  j a v  a2s .c  o m
        ClassLoader cl = getClass().getClassLoader();
        ri.setEntityClazz((Class<? extends Shareable>) cl.loadClass(ri.getEntityClassName()));
        ri.setDaoClazz((Class<? extends DTO>) cl.loadClass(ri.getDtoClassName()));
        ri.setRequestClazz(cl.loadClass(ri.getRequestClassName()));
        ri.setResponseClazz(cl.loadClass(ri.getResponseClassName()));
    } catch (ClassNotFoundException e) {
        log.warn("Can't load classes of Replication info with id {}", e, ri.getId());
    }
    return ri;

}

From source file:com.haulmont.cuba.web.sys.singleapp.SingleAppWebServletListener.java

@Override
public void contextInitialized(ServletContextEvent sce) {
    try {//from  w  w w  . j  a  v  a 2  s  . c o  m
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        //need to put the following class to WebAppClassLoader, to share it between for web and core
        contextClassLoader.loadClass("com.haulmont.cuba.core.sys.remoting.LocalServiceDirectory");

        ServletContext servletContext = sce.getServletContext();
        String dependenciesFile;
        try {
            dependenciesFile = IOUtils.toString(servletContext.getResourceAsStream("/WEB-INF/web.dependencies"),
                    "UTF-8");
        } catch (IOException e) {
            throw new RuntimeException("An error occurred while loading dependencies file", e);
        }

        String[] dependenciesNames = dependenciesFile.split("\\n");
        URL[] urls = Arrays.stream(dependenciesNames).map((String name) -> {
            try {
                return servletContext.getResource("/WEB-INF/lib/" + name);
            } catch (MalformedURLException e) {
                throw new RuntimeException("An error occurred while loading dependency " + name, e);
            }
        }).toArray(URL[]::new);
        URLClassLoader webClassLoader = new CubaSingleAppClassLoader(urls, contextClassLoader);

        Thread.currentThread().setContextClassLoader(webClassLoader);
        Class<?> appContextLoaderClass = webClassLoader.loadClass(getAppContextLoaderClassName());
        appContextLoader = appContextLoaderClass.newInstance();

        Method setJarsNamesMethod = ReflectionUtils.findMethod(appContextLoaderClass, "setJarNames",
                String.class);
        ReflectionUtils.invokeMethod(setJarsNamesMethod, appContextLoader, dependenciesFile);

        Method contextInitializedMethod = ReflectionUtils.findMethod(appContextLoaderClass,
                "contextInitialized", ServletContextEvent.class);
        ReflectionUtils.invokeMethod(contextInitializedMethod, appContextLoader, sce);

        Thread.currentThread().setContextClassLoader(contextClassLoader);
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        throw new RuntimeException("An error occurred while starting single WAR application", e);
    }
}

From source file:com.googlecode.jsonschema2pojo.integration.PropertiesIT.java

@Test
@SuppressWarnings("rawtypes")
public void propertiesWithNullValuesAreOmittedWhenSerialized() throws ClassNotFoundException,
        IntrospectionException, InstantiationException, IllegalAccessException, InvocationTargetException {

    ClassLoader resultsClassLoader = generateAndCompile("/schema/properties/nullProperties.json",
            "com.example");

    Class generatedType = resultsClassLoader.loadClass("com.example.NullProperties");
    Object instance = generatedType.newInstance();

    Method setter = new PropertyDescriptor("property", generatedType).getWriteMethod();
    setter.invoke(instance, "value");

    assertThat(mapper.valueToTree(instance).toString(), containsString("property"));

    setter.invoke(instance, (Object) null);

    assertThat(mapper.valueToTree(instance).toString(), not(containsString("property")));

}

From source file:com.quinsoft.zeidon.dbhandler.JdbcHandlerUtils.java

@SuppressWarnings("unchecked")
public DbHandler getDbHandler() {
    DbHandler handler = options.getDbHandler();
    if (handler != null)
        return handler;

    String handlerName = options.getConfigValue(getGroupName(), "DbHandler");

    // If the handler name isn't specified we'll try to be smart and determine the default
    // handler using the connection string.
    if (StringUtils.isBlank(handlerName)) {
        String conn = options.getOiSourceUrl();
        if (conn.startsWith("jdbc:mysql:"))
            handlerName = MysqlJdbcHandler.class.getCanonicalName();
        else if (conn.startsWith("jdbc:sqlite:"))
            handlerName = SqliteJdbcHandler.class.getCanonicalName();
        else if (conn.startsWith("testsql:"))
            handlerName = TestSqlHandler.class.getCanonicalName();
        else//from   w  w w .j  a  va2s .c  o  m
            handlerName = JdbcHandler.class.getCanonicalName();
    }

    try {
        // For now we assume the DBHandler is the JDBC handler.
        ClassLoader loader = options.getTask().getObjectEngine().getClassLoader(handlerName);
        Class<? extends JdbcHandler> handlerClass;
        handlerClass = (Class<? extends JdbcHandler>) loader.loadClass(handlerName);
        Constructor<? extends JdbcHandler> constructor = handlerClass.getConstructor(handlerConstructorArgs);
        JdbcHandler jdbcHandler = constructor.newInstance(options.getTask(), options);
        return jdbcHandler;
    } catch (Exception e) {
        throw ZeidonException.wrapException(e).appendMessage("Handler name = ", handlerName);
    }
}

From source file:org.jsonschema2pojo.integration.config.AnnotationStyleIT.java

@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void defaultAnnotationStyeIsJackson2()
        throws ClassNotFoundException, SecurityException, NoSuchMethodException {

    ClassLoader resultsClassLoader = schemaRule
            .generateAndCompile("/schema/properties/primitiveProperties.json", "com.example");

    Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties");

    Method getter = generatedType.getMethod("getA");

    assertThat(generatedType.getAnnotation(JsonPropertyOrder.class), is(notNullValue()));
    assertThat(generatedType.getAnnotation(JsonInclude.class), is(notNullValue()));
    assertThat(getter.getAnnotation(JsonProperty.class), is(notNullValue()));
}

From source file:com.haulmont.cuba.core.sys.singleapp.SingleAppCoreServletListener.java

@Override
public void contextInitialized(ServletContextEvent sce) {
    try {/*  w w  w .  java 2s  . c  o m*/
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        //need to put the following class to WebAppClassLoader, to share it between for web and core
        contextClassLoader.loadClass("com.haulmont.cuba.core.sys.remoting.LocalServiceDirectory");

        ServletContext servletContext = sce.getServletContext();
        String dependenciesFile;
        try {
            dependenciesFile = IOUtils
                    .toString(servletContext.getResourceAsStream("/WEB-INF/core.dependencies"), "UTF-8");
        } catch (IOException e) {
            throw new RuntimeException("An error occurred while loading dependencies file", e);
        }

        String[] dependenciesNames = dependenciesFile.split("\\n");
        URL[] urls = Arrays.stream(dependenciesNames).map((String name) -> {
            try {
                return servletContext.getResource("/WEB-INF/lib/" + name);
            } catch (MalformedURLException e) {
                throw new RuntimeException("An error occurred while loading dependency " + name, e);
            }
        }).toArray(URL[]::new);
        URLClassLoader coreClassLoader = new CubaSingleAppClassLoader(urls, contextClassLoader);

        Thread.currentThread().setContextClassLoader(coreClassLoader);
        Class<?> appContextLoaderClass = coreClassLoader.loadClass(getAppContextLoaderClassName());
        appContextLoader = appContextLoaderClass.newInstance();

        Method setJarsNamesMethod = ReflectionUtils.findMethod(appContextLoaderClass, "setJarNames",
                String.class);
        ReflectionUtils.invokeMethod(setJarsNamesMethod, appContextLoader, dependenciesFile);

        Method contextInitializedMethod = ReflectionUtils.findMethod(appContextLoaderClass,
                "contextInitialized", ServletContextEvent.class);
        ReflectionUtils.invokeMethod(contextInitializedMethod, appContextLoader, sce);

        Thread.currentThread().setContextClassLoader(contextClassLoader);
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        throw new RuntimeException("An error occurred while starting single WAR application", e);
    }
}

From source file:com.googlecode.jsonschema2pojo.integration.PropertiesIT.java

@Test
public void propertyCalledClassCanBeSerialized()
        throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {

    ClassLoader resultsClassLoader = generateAndCompile("/schema/properties/propertyCalledClass.json",
            "com.example");

    Class<?> generatedType = resultsClassLoader.loadClass("com.example.PropertyCalledClass");

    String valuesAsJsonString = "{\"class\":\"a\"}";
    Object valuesAsObject = mapper.readValue(valuesAsJsonString, generatedType);
    JsonNode valueAsJsonNode = mapper.valueToTree(valuesAsObject);

    assertThat(valueAsJsonNode.path("class").asText(), is("a"));

}