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.freetmp.common.util.ClassUtils.java

public static Class<?> forName(String name, ClassLoader classLoader)
        throws ClassNotFoundException, LinkageError {
    Assert.notNull(name, "Name must not be null");

    Class<?> clazz = resolvePrimitiveClassName(name);
    if (clazz == null) {
        clazz = commonClassCache.get(name);
    }/*ww  w  .j a va 2  s. c o m*/
    if (clazz != null) {
        return clazz;
    }

    // "java.lang.String[]" style arrays
    if (name.endsWith(ARRAY_SUFFIX)) {
        String elementClassName = name.substring(0, name.length() - ARRAY_SUFFIX.length());
        Class<?> elementClass = forName(elementClassName, classLoader);
        return Array.newInstance(elementClass, 0).getClass();
    }

    // "[Ljava.lang.String;" style arrays
    if (name.startsWith(NON_PRIMITIVE_ARRAY_PREFIX) && name.endsWith(";")) {
        String elementName = name.substring(NON_PRIMITIVE_ARRAY_PREFIX.length(), name.length() - 1);
        Class<?> elementClass = forName(elementName, classLoader);
        return Array.newInstance(elementClass, 0).getClass();
    }

    // "[[I" or "[[Ljava.lang.String;" style arrays
    if (name.startsWith(INTERNAL_ARRAY_PREFIX)) {
        String elementName = name.substring(INTERNAL_ARRAY_PREFIX.length());
        Class<?> elementClass = forName(elementName, classLoader);
        return Array.newInstance(elementClass, 0).getClass();
    }

    ClassLoader clToUse = classLoader;
    if (clToUse == null) {
        clToUse = getDefaultClassLoader();
    }
    try {
        return (clToUse != null ? clToUse.loadClass(name) : Class.forName(name));
    } catch (ClassNotFoundException ex) {
        int lastDotIndex = name.lastIndexOf(PACKAGE_SEPARATOR);
        if (lastDotIndex != -1) {
            String innerClassName = name.substring(0, lastDotIndex) + INNER_CLASS_SEPARATOR
                    + name.substring(lastDotIndex + 1);
            try {
                return (clToUse != null ? clToUse.loadClass(innerClassName) : Class.forName(innerClassName));
            } catch (ClassNotFoundException ex2) {
                // Swallow - let original exception get through
            }
        }
        throw ex;
    }
}

From source file:org.jsonschema2pojo.integration.JavaNameIT.java

@Test
public void settersHaveCorrectNamesAndArgumentTypes()
        throws NoSuchMethodException, ClassNotFoundException, IllegalAccessException, InstantiationException {

    ClassLoader javaNameClassLoader = schemaRule.generateAndCompile("/schema/javaName/javaName.json",
            "com.example.javaname");
    Class<?> classWithJavaNames = javaNameClassLoader.loadClass("com.example.javaname.JavaName");

    classWithJavaNames.getMethod("setJavaProperty", String.class);
    classWithJavaNames.getMethod("setPropertyWithoutJavaName", String.class);

    classWithJavaNames.getMethod("setJavaEnum",
            javaNameClassLoader.loadClass("com.example.javaname.JavaName$JavaEnum"));
    classWithJavaNames.getMethod("setEnumWithoutJavaName",
            javaNameClassLoader.loadClass("com.example.javaname.JavaName$EnumWithoutJavaName"));

    classWithJavaNames.getMethod("setJavaObject",
            javaNameClassLoader.loadClass("com.example.javaname.JavaObject"));
    classWithJavaNames.getMethod("setObjectWithoutJavaName",
            javaNameClassLoader.loadClass("com.example.javaname.ObjectWithoutJavaName"));

}

From source file:fr.inria.atlanmod.neoemf.data.blueprints.BlueprintsPersistenceBackendFactory.java

private PropertiesConfiguration getOrCreateBlueprintsConfiguration(File directory, Map<?, ?> options)
        throws InvalidDataStoreException {
    PropertiesConfiguration configuration;

    // Try to load previous configurations
    Path path = Paths.get(directory.getAbsolutePath()).resolve(BLUEPRINTS_CONFIG_FILE);
    try {//from  w  w w . java 2 s. co m
        configuration = new PropertiesConfiguration(path.toFile());
    } catch (ConfigurationException e) {
        throw new InvalidDataStoreException(e);
    }

    // Initialize value if the config file has just been created
    if (!configuration.containsKey(BlueprintsResourceOptions.GRAPH_TYPE)) {
        configuration.setProperty(BlueprintsResourceOptions.GRAPH_TYPE,
                BlueprintsResourceOptions.GRAPH_TYPE_DEFAULT);
    } else if (options.containsKey(BlueprintsResourceOptions.GRAPH_TYPE)) {
        // The file already existed, check that the issued options are not conflictive
        String savedGraphType = configuration.getString(BlueprintsResourceOptions.GRAPH_TYPE);
        String issuedGraphType = options.get(BlueprintsResourceOptions.GRAPH_TYPE).toString();
        if (!Objects.equals(savedGraphType, issuedGraphType)) {
            NeoLogger.error("Unable to create graph as type {0}, expected graph type was {1})", issuedGraphType,
                    savedGraphType);
            throw new InvalidDataStoreException("Unable to create graph as type " + issuedGraphType
                    + ", expected graph type was " + savedGraphType + ')');
        }
    }

    // Copy the options to the configuration
    for (Entry<?, ?> e : options.entrySet()) {
        configuration.setProperty(e.getKey().toString(), e.getValue().toString());
    }

    // Check we have a valid graph type, it is needed to get the graph name
    String graphType = configuration.getString(BlueprintsResourceOptions.GRAPH_TYPE);
    if (isNull(graphType)) {
        throw new InvalidDataStoreException("Graph type is undefined for " + directory.getAbsolutePath());
    }

    // Define the configuration
    String[] segments = graphType.split("\\.");
    if (segments.length >= 2) {
        String graphName = segments[segments.length - 2];
        String upperCaseGraphName = Character.toUpperCase(graphName.charAt(0)) + graphName.substring(1);
        String configClassName = MessageFormat.format("InternalBlueprints{0}Configuration", upperCaseGraphName);
        String configClassQualifiedName = MessageFormat
                .format("fr.inria.atlanmod.neoemf.data.blueprints.{0}.config.{1}", graphName, configClassName);

        try {
            ClassLoader classLoader = BlueprintsPersistenceBackendFactory.class.getClassLoader();
            Class<?> configClass = classLoader.loadClass(configClassQualifiedName);
            Method configClassInstanceMethod = configClass.getMethod("getInstance");
            InternalBlueprintsConfiguration blueprintsConfig = (InternalBlueprintsConfiguration) configClassInstanceMethod
                    .invoke(configClass);
            blueprintsConfig.putDefaultConfiguration(configuration, directory);
        } catch (ClassNotFoundException e) {
            NeoLogger.warn(e, "Unable to find the configuration class {0}", configClassQualifiedName);
        } catch (NoSuchMethodException e) {
            NeoLogger.warn(e, "Unable to find configuration methods in class {0}", configClassName);
        } catch (InvocationTargetException | IllegalAccessException e) {
            NeoLogger.warn(e, "An error occurs during the execution of a configuration method");
        }
    } else {
        NeoLogger.warn("Unable to compute graph type name from {0}", graphType);
    }

    return configuration;
}

From source file:hermes.impl.ConnectionFactoryManagerImpl.java

public void setProvider(ProviderConfig pConfig) throws InstantiationException, ClassNotFoundException,
        IllegalAccessException, InvocationTargetException, NoSuchMethodException, IOException {
    ClassLoader classLoader = classLoaderManager.getClassLoader(factoryConfig.getClasspathId());
    connectionFactory = ReflectUtils.createConnectionFactory(classLoader.loadClass(pConfig.getClassName()));

    LoaderSupport.populateBean(connectionFactory, pConfig.getProperties());
    setConnectionFactory(connectionFactory);
}

From source file:fr.mby.utils.spring.beans.factory.annotation.ProxywiredAnnotationBeanPostProcessor.java

/**
 * Copy paste from AutowiredAnnotationBeanPostProcessor with Proxywired type added.
 */// www .  j a  v  a 2  s  . c  om
@SuppressWarnings("unchecked")
protected ProxywiredAnnotationBeanPostProcessor() {
    super();

    final Set<Class<? extends Annotation>> autowiredAnnotationTypes = new LinkedHashSet<Class<? extends Annotation>>();
    autowiredAnnotationTypes.add(Autowired.class);
    autowiredAnnotationTypes.add(Value.class);
    autowiredAnnotationTypes.add(ProxywiredAnnotationBeanPostProcessor.PROXY_ANNOTATION);
    final ClassLoader cl = AutowiredAnnotationBeanPostProcessor.class.getClassLoader();
    try {
        autowiredAnnotationTypes.add((Class<? extends Annotation>) cl.loadClass("javax.inject.Inject"));
        this.logger.info("JSR-330 'javax.inject.Inject' annotation found and supported for autowiring");
    } catch (final ClassNotFoundException ex) {
        // JSR-330 API not available - simply skip.
    }

    super.setAutowiredAnnotationTypes(autowiredAnnotationTypes);
}

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

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

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile(
            "/schema/properties/primitiveProperties.json", "com.example", config("annotationStyle", "none")); // turn off core annotations

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

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

    assertThat(generatedType.getAnnotations().length, is(0));
    assertThat(getter.getAnnotations().length, is(0));
}

From source file:org.crazydog.util.spring.ClassUtils.java

/**
 * Replacement for {@code Class.forName()} that also returns Class instances
 * for primitives (e.g. "int") and array class names (e.g. "String[]").
 * Furthermore, it is also capable of resolving inner class names in Java source
 * style (e.g. "java.lang.Thread.State" instead of "java.lang.Thread$State").
 * @param name the name of the Class/*  w  w w. j  a  v  a2s.c o  m*/
 * @param classLoader the class loader to use
 * (may be {@code null}, which indicates the default class loader)
 * @return Class instance for the supplied name
 * @throws ClassNotFoundException if the class was not found
 * @throws LinkageError if the class file could not be loaded
 * @see Class#forName(String, boolean, ClassLoader)
 */
public static Class<?> forName(String name, ClassLoader classLoader)
        throws ClassNotFoundException, LinkageError {
    org.springframework.util.Assert.notNull(name, "Name must not be null");

    Class<?> clazz = resolvePrimitiveClassName(name);
    if (clazz == null) {
        clazz = commonClassCache.get(name);
    }
    if (clazz != null) {
        return clazz;
    }

    // "java.lang.String[]" style arrays
    if (name.endsWith(ARRAY_SUFFIX)) {
        String elementClassName = name.substring(0, name.length() - ARRAY_SUFFIX.length());
        Class<?> elementClass = forName(elementClassName, classLoader);
        return Array.newInstance(elementClass, 0).getClass();
    }

    // "[Ljava.lang.String;" style arrays
    if (name.startsWith(NON_PRIMITIVE_ARRAY_PREFIX) && name.endsWith(";")) {
        String elementName = name.substring(NON_PRIMITIVE_ARRAY_PREFIX.length(), name.length() - 1);
        Class<?> elementClass = forName(elementName, classLoader);
        return Array.newInstance(elementClass, 0).getClass();
    }

    // "[[I" or "[[Ljava.lang.String;" style arrays
    if (name.startsWith(INTERNAL_ARRAY_PREFIX)) {
        String elementName = name.substring(INTERNAL_ARRAY_PREFIX.length());
        Class<?> elementClass = forName(elementName, classLoader);
        return Array.newInstance(elementClass, 0).getClass();
    }

    ClassLoader clToUse = classLoader;
    if (clToUse == null) {
        clToUse = getDefaultClassLoader();
    }
    try {
        return (clToUse != null ? clToUse.loadClass(name) : Class.forName(name));
    } catch (ClassNotFoundException ex) {
        int lastDotIndex = name.lastIndexOf(PACKAGE_SEPARATOR);
        if (lastDotIndex != -1) {
            String innerClassName = name.substring(0, lastDotIndex) + INNER_CLASS_SEPARATOR
                    + name.substring(lastDotIndex + 1);
            try {
                return (clToUse != null ? clToUse.loadClass(innerClassName) : Class.forName(innerClassName));
            } catch (ClassNotFoundException ex2) {
                // Swallow - let original exception get through
            }
        }
        throw ex;
    }
}

From source file:org.jsonschema2pojo.integration.json.JsonTypesIT.java

@Test
@SuppressWarnings("unchecked")
public void complexTypesProduceObjects() throws Exception {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/json/complexObject.json", "com.example",
            config("sourceType", "json"));

    Class<?> complexObjectClass = resultsClassLoader.loadClass("com.example.ComplexObject");
    Object complexObject = OBJECT_MAPPER
            .readValue(this.getClass().getResourceAsStream("/json/complexObject.json"), complexObjectClass);

    Object a = complexObjectClass.getMethod("getA").invoke(complexObject);
    Object aa = a.getClass().getMethod("getAa").invoke(a);
    assertThat(aa.getClass().getMethod("getAaa").invoke(aa).toString(), is("aaaa"));

    Object b = complexObjectClass.getMethod("getB").invoke(complexObject);
    assertThat(b.getClass().getMethod("getAa").invoke(b), is(notNullValue()));

    Object _1 = complexObjectClass.getMethod("get1").invoke(complexObject);
    Object _2 = _1.getClass().getMethod("get2").invoke(_1);
    assertThat(_2, is(notNullValue()));/*from   w  ww  .j av  a  2 s  . c o m*/
    Object _3 = _1.getClass().getMethod("get3").invoke(_1);
    assertThat((List<Integer>) _3, is(equalTo(asList(1, 2, 3))));

}

From source file:edu.internet2.middleware.shibboleth.common.config.attribute.resolver.dataConnector.StoredIDDataConnectorBeanDefinitionParser.java

/**
 * Builds a JDBC {@link javax.sql.DataSource} from an ApplicationManagedConnection configuration element.
 * /* w  w w. ja  va2 s.com*/
 * @param pluginId ID of this data connector
 * @param amc the application managed configuration element
 * 
 * @return the built data source
 */
protected DataSource buildApplicationManagedConnection(String pluginId, Element amc) {
    ComboPooledDataSource datasource = new ComboPooledDataSource();

    String driverClass = DatatypeHelper.safeTrim(amc.getAttributeNS(null, "jdbcDriver"));
    ClassLoader classLoader = this.getClass().getClassLoader();
    try {
        classLoader.loadClass(driverClass);
    } catch (ClassNotFoundException e) {
        log.error(
                "Unable to create relational database connector, JDBC driver can not be found on the classpath");
        throw new BeanCreationException(
                "Unable to create relational database connector, JDBC driver can not be found on the classpath");
    }

    try {
        datasource.setDriverClass(driverClass);
        datasource.setJdbcUrl(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "jdbcURL")));
        datasource.setUser(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "jdbcUserName")));
        datasource.setPassword(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "jdbcPassword")));

        if (amc.hasAttributeNS(null, "poolAcquireIncrement")) {
            datasource.setAcquireIncrement(Integer
                    .parseInt(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "poolAcquireIncrement"))));
        } else {
            datasource.setAcquireIncrement(3);
        }

        if (amc.hasAttributeNS(null, "poolAcquireRetryAttempts")) {
            datasource.setAcquireRetryAttempts(Integer
                    .parseInt(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "poolAcquireRetryAttempts"))));
        } else {
            datasource.setAcquireRetryAttempts(36);
        }

        if (amc.hasAttributeNS(null, "poolAcquireRetryDelay")) {
            datasource.setAcquireRetryDelay(Integer
                    .parseInt(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "poolAcquireRetryDelay"))));
        } else {
            datasource.setAcquireRetryDelay(5000);
        }

        if (amc.hasAttributeNS(null, "poolBreakAfterAcquireFailure")) {
            datasource.setBreakAfterAcquireFailure(XMLHelper
                    .getAttributeValueAsBoolean(amc.getAttributeNodeNS(null, "poolBreakAfterAcquireFailure")));
        } else {
            datasource.setBreakAfterAcquireFailure(true);
        }

        if (amc.hasAttributeNS(null, "poolMinSize")) {
            datasource.setMinPoolSize(
                    Integer.parseInt(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "poolMinSize"))));
        } else {
            datasource.setMinPoolSize(2);
        }

        if (amc.hasAttributeNS(null, "poolMaxSize")) {
            datasource.setMaxPoolSize(
                    Integer.parseInt(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "poolMaxSize"))));
        } else {
            datasource.setMaxPoolSize(50);
        }

        if (amc.hasAttributeNS(null, "poolMaxIdleTime")) {
            datasource.setMaxIdleTime(
                    Integer.parseInt(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "poolMaxIdleTime"))));
        } else {
            datasource.setMaxIdleTime(600);
        }

        if (amc.hasAttributeNS(null, "poolIdleTestPeriod")) {
            datasource.setIdleConnectionTestPeriod(
                    Integer.parseInt(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "poolIdleTestPeriod"))));
        } else {
            datasource.setIdleConnectionTestPeriod(180);
        }

        datasource.setMaxStatementsPerConnection(10);

        log.debug("Created application managed data source for data connector {}", pluginId);
        return datasource;
    } catch (PropertyVetoException e) {
        log.error("Unable to create data source for data connector {} with JDBC driver class {}", pluginId,
                driverClass);
        return null;
    }
}

From source file:org.jsonschema2pojo.integration.json.JsonTypesIT.java

@Test
public void integerIsMappedToBigInteger() throws Exception {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/json/simpleTypes.json", "com.example",
            config("sourceType", "json", "useBigIntegers", true));

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

    Object deserialisedValue = OBJECT_MAPPER
            .readValue(this.getClass().getResourceAsStream("/json/simpleTypes.json"), generatedType);

    assertThat((BigInteger) generatedType.getMethod("getB").invoke(deserialisedValue),
            is(new BigInteger("123")));
}