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:net.freifunk.autodeploy.AutoDeployModule.java

@Provides
@Singleton//from  www .  java  2 s . com
private WebDriver provideWebDriver() {
    final WebDriver webDriver;

    if ("true".equals(System.getProperty("webdriver.firefox.enable"))) {
        try {
            final ClassLoader classLoader = this.getClass().getClassLoader();
            @SuppressWarnings("unchecked")
            final Class<? extends WebDriver> firefoxDriverClass = (Class<? extends WebDriver>) classLoader
                    .loadClass("org.openqa.selenium.firefox.FirefoxDriver");
            final WebDriver firefoxDriver = firefoxDriverClass.newInstance();
            webDriver = firefoxDriver;
        } catch (final ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            throw new IllegalStateException(
                    "Trying to instantiate FirefoxDriver failed. Did you compile with -Dwebdriver.firefox.allow=true?",
                    e);
        }
    } else {
        final HtmlUnitDriver htmlUnitDriver = new HeadlessDriver();
        webDriver = htmlUnitDriver;
    }

    LOG.debug("WebDriver being used: " + webDriver.getClass().getSimpleName());
    return webDriver;
}

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

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

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

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

    new PropertyDescriptor("type", generatedType).getWriteMethod().invoke(instance, "1");
    new PropertyDescriptor("id", generatedType).getWriteMethod().invoke(instance, "2");
    new PropertyDescriptor("name", generatedType).getWriteMethod().invoke(instance, "3");
    new PropertyDescriptor("hastickets", generatedType).getWriteMethod().invoke(instance, true);
    new PropertyDescriptor("starttime", generatedType).getWriteMethod().invoke(instance, "4");

    String serialized = mapper.valueToTree(instance).toString();

    assertThat("Properties are not in expected order", serialized.indexOf("type"),
            is(lessThan(serialized.indexOf("id"))));
    assertThat("Properties are not in expected order", serialized.indexOf("id"),
            is(lessThan(serialized.indexOf("name"))));
    assertThat("Properties are not in expected order", serialized.indexOf("name"),
            is(lessThan(serialized.indexOf("hastickets"))));
    assertThat("Properties are not in expected order", serialized.indexOf("hastickets"),
            is(lessThan(serialized.indexOf("starttime"))));

}

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

@Test
@SuppressWarnings("unchecked")
public void enumAtRootCreatesATopLevelType() throws ClassNotFoundException, NoSuchMethodException,
        IllegalAccessException, InvocationTargetException {

    ClassLoader resultsClassLoader = generateAndCompile("/schema/enum/enumAsRoot.json", "com.example");

    Class<Enum> rootEnumClass = (Class<Enum>) resultsClassLoader.loadClass("com.example.enums.EnumAsRoot");

    assertThat(rootEnumClass.isEnum(), is(true));
    assertThat(isPublic(rootEnumClass.getModifiers()), is(true));

}

From source file:com.sachviet.bookman.server.util.ResolverUtil.java

@SuppressWarnings("unchecked")
protected void addIfMatching(String fqn, Test... tests) {
    try {/*from  www  .  j a va 2s . co  m*/
        String externalName = fqn.substring(0, fqn.indexOf('.')).replace('/', '.');
        ClassLoader loader = getClassLoader();

        Class<?> type = loader.loadClass(externalName);

        for (Test test : tests) {
            if (test.matches(type)) {
                matches.add((Class<T>) type);
                if (LOG.isDebugEnabled()) {
                    LOG.info("Found JDBC driver :" + type.getName()); //$NON-NLS-1$
                }
            }
        }
    } catch (Throwable t) {
        //      log.trace("Could not examine class \\\'" + fqn + "\\\' due to a " //$NON-NLS-1$ //$NON-NLS-2$
        //          + t.getClass().getName() + " with message: " //$NON-NLS-1$
        // + t.getMessage());
    }
}

From source file:com.cedarsoft.codegen.AbstractGenerator.java

@Nonnull
public Class<?> getRunnerType() throws ToolsJarNotFoundException, ClassNotFoundException {
    ClassLoader aptClassLoader = createAptClassLoader();
    Thread.currentThread().setContextClassLoader(aptClassLoader);

    return aptClassLoader.loadClass(getRunnerClassName());
}

From source file:org.apache.batchee.cli.lifecycle.impl.SpringLifecycle.java

@Override
public AbstractApplicationContext start() {
    final Map<String, Object> config = configuration("spring");

    final AbstractApplicationContext ctx;
    if (config.containsKey("locations")) {
        final Collection<String> locations = new LinkedList<String>();
        locations.addAll(asList(config.get("locations").toString().split(",")));
        ctx = new ClassPathXmlApplicationContext(locations.toArray(new String[locations.size()]));
    } else if (config.containsKey("classes")) {
        final Collection<Class<?>> classes = new LinkedList<Class<?>>();
        final ClassLoader loader = currentThread().getContextClassLoader();
        for (final String clazz : config.get("classes").toString().split(",")) {
            try {
                classes.add(loader.loadClass(clazz));
            } catch (final ClassNotFoundException e) {
                throw new BatchContainerRuntimeException(e);
            }// w  ww . j a  va  2 s.  c o m
        }
        ctx = new AnnotationConfigApplicationContext(classes.toArray(new Class<?>[classes.size()]));
    } else {
        throw new IllegalArgumentException(
                LIFECYCLE_PROPERTIES_FILE + " should contain 'classes' or 'locations' key");
    }

    final Properties p = new Properties();
    p.put(BatchArtifactFactory.class.getName(), new SpringArtifactFactory(ctx));

    final ServicesManager mgr = new ServicesManager();
    mgr.init(p);

    ServicesManager.setServicesManagerLocator(new ServicesManagerLocator() {
        @Override
        public ServicesManager find() {
            return mgr;
        }
    });

    return ctx;
}

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

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

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

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

    String valuesAsJsonString = "{\"public\":\"a\",\"void\":\"b\",\"enum\":\"c\",\"abstract\":\"d\"}";
    Object valuesAsObject = mapper.readValue(valuesAsJsonString, generatedType);
    JsonNode valueAsJsonNode = mapper.valueToTree(valuesAsObject);

    assertThat(valueAsJsonNode.path("public").asText(), is("a"));
    assertThat(valueAsJsonNode.path("void").asText(), is("b"));
    assertThat(valueAsJsonNode.path("enum").asText(), is("c"));
    assertThat(valueAsJsonNode.path("abstract").asText(), is("d"));

}

From source file:com.streamsets.pipeline.maven.rbgen.RBGenMojo.java

private boolean usesDataCollectorAPI(ClassLoader classLoader) {
    try {/*w  w w.  j  a v a  2s  . c  o m*/
        stageClass = classLoader.loadClass(STAGE_CLASS_NAME);
        errorCodeClass = classLoader.loadClass(ERROR_CODE_CLASS_NAME);
        labelClass = classLoader.loadClass(LABEL_CLASS_NAME);
        stageDefClass = classLoader.loadClass(STAGE_DEF_CLASS_NAME);
        errorStageClass = classLoader.loadClass(ERROR_STAGE_CLASS_NAME);
        configDefClass = classLoader.loadClass(CONFIG_DEF_CLASS_NAME);
        return true;
    } catch (ClassNotFoundException ex) {
        return false;
    }
}

From source file:com.google.gdt.eclipse.designer.model.widgets.cell.AbstractCellTableInfo.java

@Override
public void createExposedChildren() throws Exception {
    super.createExposedChildren();
    // create exposed columns
    ClassLoader editorLoader = JavaInfoUtils.getClassLoader(this);
    Class<?> columnClass = editorLoader.loadClass("com.google.gwt.user.cellview.client.Column");
    JavaInfoUtils.addExposedChildren(this, new Class<?>[] { columnClass });
}

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

@Test
@SuppressWarnings("unchecked")
public void enumWithNullValue() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException,
        InvocationTargetException {

    ClassLoader resultsClassLoader = generateAndCompile("/schema/enum/enumWithNullValue.json", "com.example");

    Class<Enum> emptyEnumClass = (Class<Enum>) resultsClassLoader.loadClass("com.example.EnumWithNullValue");

    assertThat(emptyEnumClass.getEnumConstants().length, is(1));

}