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:gr.upatras.ece.nam.fci.core.FCI.java

/**
 * @return //from  w w  w  .j  a  v  a2s .c  o  m
 * 
 */

public void loadUoPService() {
    ClassLoader classLoader = FCI.class.getClassLoader();

    //Dynamic loading UoPServices plugin if exists
    Class<?> ServicesClass;
    try {
        ServicesClass = classLoader.loadClass("gr.upatras.ece.nam.fci.uop.UoPServices");
        log.info("Found aClass.getName() = " + ServicesClass.getName());
        iUoPServices = (IFCIService) ServicesClass.newInstance();

    } catch (ClassNotFoundException e1) {
        //e1.printStackTrace();
        log.warn("UoPServices class not found");
    } catch (InstantiationException e) {
        // TODO Auto-generated catch block
        //         e.printStackTrace();

        log.warn("UoPServices class not instantiated");
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:gr.upatras.ece.nam.fci.core.FCI.java

public void loadAmazonService() {
    ClassLoader classLoader = FCI.class.getClassLoader();

    //Dynamic loading UoPServices plugin if exists
    Class<?> ServicesClass;
    try {/* w  w  w. j  a  v  a2s.c  o  m*/

        ServicesClass = classLoader.loadClass("gr.upatras.ece.nam.fci.amazon.AmazonServices");
        log.info("Found aClass.getName() = " + ServicesClass.getName());
        iAmazonServices = (IFCIService) ServicesClass.newInstance();

    } catch (ClassNotFoundException e1) {
        //e1.printStackTrace();
        log.warn("AmazonServices class not found");
    } catch (InstantiationException e) {
        // TODO Auto-generated catch block
        //         e.printStackTrace();

        log.warn("AmazonServices class not instantiated");
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:gr.upatras.ece.nam.fci.core.FCI.java

public void loadSFAService() {
    ClassLoader classLoader = FCI.class.getClassLoader();

    //Dynamic loading UoPServices plugin if exists
    Class<?> ServicesClass;
    try {// w  w w . ja v  a  2  s .  c om

        ServicesClass = classLoader.loadClass("gr.upatras.ece.nam.fci.sfa.SFAServices");
        log.info("Found aClass.getName() = " + ServicesClass.getName());
        iSFAServices = (IFCIService) ServicesClass.newInstance();

    } catch (ClassNotFoundException e1) {
        //e1.printStackTrace();
        log.warn("SFAServices class not found");
    } catch (InstantiationException e) {
        // TODO Auto-generated catch block
        //         e.printStackTrace();

        log.warn("SFAServices class not instantiated");
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:gr.upatras.ece.nam.fci.core.FCI.java

public void loadPanlabService() {
    ClassLoader classLoader = FCI.class.getClassLoader();

    //Dynamic loading UoPServices plugin if exists
    Class<?> ServicesClass;
    try {//from w ww  . j  ava 2  s .c o m

        ServicesClass = classLoader.loadClass("gr.upatras.ece.nam.fci.panlab.PanlabServices");
        log.info("Found aClass.getName() = " + ServicesClass.getName());
        iPanlabServices = (IFCIService) ServicesClass.newInstance();

    } catch (ClassNotFoundException e1) {
        //e1.printStackTrace();
        log.warn("PanlabServices class not found");
    } catch (InstantiationException e) {
        // TODO Auto-generated catch block
        //         e.printStackTrace();

        log.warn("PanlabServices class not instantiated");
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.google.gdt.eclipse.designer.hosted.tdt.HostedModeSupport.java

public void dispose() {
    if (moduleSpaceHost != null) {
        // clear static caches
        ClassLoader devClassLoader = getDevClassLoader();
        try {//from w  w  w . j a  v a 2  s  .co m
            Class<?> clazz = devClassLoader.loadClass("com.google.gwt.i18n.rebind.ClearStaticData");
            ReflectionUtils.invokeMethod2(clazz, "clear");
        } catch (Throwable e) {
        }
        try {
            Class<?> clazz = devClassLoader.loadClass("com.google.gwt.uibinder.rebind.model.OwnerFieldClass");
            Map<?, ?> map = (Map<?, ?>) ReflectionUtils.getFieldObject(clazz, "FIELD_CLASSES");
            map.clear();
        } catch (Throwable e) {
        }
        // remove parent of CompilingClassLoader
        if (parentClassLoader != null) {
            ClassLoader classLoader = getClassLoader();
            ReflectionUtils.setField(classLoader, "parent", null);
        }
        // clear "loadedModulesCaches" in com.google.gwt.dev.cfg.ModuleDefLoader
        try {
            Class<?> moduleDefLoader = devClassLoader.loadClass("com.google.gwt.dev.cfg.ModuleDefLoader");
            Map<?, ?> loadedModulesCaches = (Map<?, ?>) ReflectionUtils.getFieldObject(moduleDefLoader,
                    "loadedModulesCaches");
            loadedModulesCaches.clear();
        } catch (Throwable e) {
        }
        /*// clear "threadLocalLogger" in com.google.gwt.dev.shell.ModuleSpace
        try {
          Class<?> classModuleSpace =
              devClassLoader.loadClass("com.google.gwt.dev.shell.ModuleSpace");
          ThreadLocal<?> threadLocalLogger =
              (ThreadLocal<?>) ReflectionUtils.getFieldObject(classModuleSpace, "threadLocalLogger");
          threadLocalLogger.set(null);
        } catch (Throwable e) {
        }
        // shutdown com.google.gwt.dev.javac.PersistentUnitCache
        try {
          Class<?> classUnitCacheFactory =
              devClassLoader.loadClass("com.google.gwt.dev.javac.UnitCacheFactory");
          Object cacheInstance = ReflectionUtils.getFieldObject(classUnitCacheFactory, "instance");
          if (cacheInstance != null) {
            Method shutdownMethod =
                ReflectionUtils.getMethodBySignature(cacheInstance.getClass(), "shutdown()");
            if (shutdownMethod != null) {
              shutdownMethod.invoke(cacheInstance);
            }
          }
          ReflectionUtils.setField(classUnitCacheFactory, "instance", null);
        } catch (Throwable e) {
        }
        // Call and remove GWT related java.lang.ApplicationShutdownHooks
        try {
          Class<?> hooksClass =
              ClassLoader.getSystemClassLoader().loadClass("java.lang.ApplicationShutdownHooks");
          Field hooksField = ReflectionUtils.getFieldByName(hooksClass, "hooks");
          @SuppressWarnings("unchecked")
          Map<Thread, ?> hooks = (Map<Thread, ?>) hooksField.get(null);
          List<Thread> threads = ImmutableList.copyOf(hooks.keySet());
          for (Thread thread : threads) {
            ClassLoader contextClassLoader = thread.getContextClassLoader();
            if (contextClassLoader == devClassLoader) {
              thread.setContextClassLoader(ClassLoader.getSystemClassLoader());
              thread.run();
              hooks.remove(thread);
            }
          }
        } catch (Throwable e) {
          e.printStackTrace();
        }
        // close com.google.gwt.dev.util.DiskCache
        try {
          Class<?> classDiskCache = devClassLoader.loadClass("com.google.gwt.dev.util.DiskCache");
          Object cacheInstance = ReflectionUtils.getFieldObject(classDiskCache, "INSTANCE");
          ReflectionUtils.invokeMethod(cacheInstance, "close()");
        } catch (Throwable e) {
        }
        // find embedded Guava Finalizer and clear reference of our "dev" URLClassLoader
        try {
          Thread[] threads = getAllThreads();
          for (Thread thread : threads) {
            if (thread != null && thread.getContextClassLoader() == devClassLoader) {
              thread.setContextClassLoader(null);
            }
          }
        } catch (Throwable e) {
        }*/
    }
    //
    if (browserShell != null) {
        browserShell.dispose();
    }
    logSupport.dispose();
    moduleSpaceHost = null;
    impl = null;
    projectClassLoader = null;
    dispatchIdOracle = null;
}

From source file:com.quinsoft.zeidon.objectdefinition.LodDef.java

private Object getConstraintObject(View view) {
    ObjectEngine oe = view.getObjectEngine();
    String className = getSourceFileName();
    if (StringUtils.isBlank(className))
        className = getApplication().getPackage() + "." + getName() + "_Object";

    try {//from   w  w  w .  j  a  v a  2s.  c  o  m
        ClassLoader classLoader = oe.getClassLoader(className);
        Class<?> operationsClass;
        operationsClass = classLoader.loadClass(className);
        Constructor<?> constructor = operationsClass.getConstructor(constructorArgTypes);
        return constructor.newInstance(view);
    } catch (Exception e) {
        throw ZeidonException.wrapException(e).prependLodDef(LodDef.this)
                .appendMessage("Class name = %s", className)
                .appendMessage("See inner exception for more info.");
    }
}

From source file:com.opengamma.maven.scripts.ScriptableScriptGeneratorMojo.java

private Map<Class<?>, Template> resolveTemplateMap(ClassLoader classLoader) throws MojoExecutionException {
    if (_baseClassTemplateMap == null || _baseClassTemplateMap.isEmpty()) {
        return ImmutableMap.<Class<?>, Template>of(Object.class, getTemplate(_template));
    }//from   ww  w .j  a  v  a 2 s . com
    Map<Class<?>, Template> templateMap = new HashMap<Class<?>, Template>();
    for (Map.Entry<String, String> unresolvedEntry : _baseClassTemplateMap.entrySet()) {
        String className = unresolvedEntry.getKey();
        Class<?> clazz;
        try {
            clazz = classLoader.loadClass(className);
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException("Unable to resolve class " + className);
        }
        Template template = getTemplate(unresolvedEntry.getValue());
        templateMap.put(clazz, template);
    }
    return templateMap;
}

From source file:cn.com.ebmp.freesql.io.ResolverUtil.java

/**
 * Add the class designated by the fully qualified class name provided to
 * the set of resolved classes if and only if it is approved by the Test
 * supplied./*w ww  .j a  va 2  s.  c o  m*/
 * 
 * @param test
 *            the test used to determine if the class matches
 * @param fqn
 *            the fully qualified name of a class
 */
@SuppressWarnings("unchecked")
protected void addIfMatching(Test test, String fqn) {
    try {
        String externalName = fqn.substring(0, fqn.indexOf('.')).replace('/', '.');
        ClassLoader loader = getClassLoader();
        log.debug("Checking to see if class " + externalName + " matches criteria [" + test + "]");

        Class type = loader.loadClass(externalName);
        if (test.matches(type)) {
            matches.add((Class<T>) type);
        }
    } catch (Throwable t) {
        log.warn("Could not examine class '" + fqn + "'" + " due to a " + t.getClass().getName()
                + " with message: " + t.getMessage());
    }
}

From source file:io.spotnext.maven.mojo.TransformTypesMojo.java

private List<ClassFileTransformer> getClassFileTransformers(final ClassLoader cl)
        throws MojoExecutionException {
    try {/*from   w  ww . j  a  v a  2s .  co m*/
        final List<URL> classPathUrls = getClasspath();

        if (CollectionUtils.isNotEmpty(classFileTransformers)) {
            final List<ClassFileTransformer> list = new ArrayList<>(classFileTransformers.size());

            for (final String classFileTransformer : classFileTransformers) {
                final Class<?> clazz = cl.loadClass(classFileTransformer);
                final ClassFileTransformer transformer = (ClassFileTransformer) clazz.newInstance();

                if (transformer instanceof AbstractBaseClassTransformer) {
                    final AbstractBaseClassTransformer baseClassTransformer = ((AbstractBaseClassTransformer) transformer);

                    baseClassTransformer.addClassPaths(project.getBuild().getOutputDirectory());
                    baseClassTransformer.addClassPaths(
                            classPathUrls.stream().map(u -> u.getFile()).collect(Collectors.toList()));
                }

                list.add(transformer);
            }

            return list;
        } else {
            getLog().warn("No class file transformers configured!");
            return Collections.emptyList();
        }
    } catch (final Exception e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:org.bytesoft.bytetcc.supports.spring.CompensableBeanFactoryPostProcessor.java

public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();

    String beanFactoryBeanId = null;
    String interceptorBeanId = null;
    List<BeanDefinition> beanFactoryAwareBeanIdList = new ArrayList<BeanDefinition>();
    String[] beanNameArray = beanFactory.getBeanDefinitionNames();
    for (int i = 0; i < beanNameArray.length; i++) {
        String beanName = beanNameArray[i];
        BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName);
        String beanClassName = beanDef.getBeanClassName();

        Class<?> beanClass = null;
        try {//  w  w  w  .  j ava  2 s .  com
            beanClass = cl.loadClass(beanClassName);
        } catch (Exception ex) {
            logger.debug("Cannot load class {}, beanId= {}!", beanClassName, beanName, ex);
            continue;
        }

        if (CompensableBeanFactoryAware.class.isAssignableFrom(beanClass)) {
            beanFactoryAwareBeanIdList.add(beanDef);
        }

        if (CompensableBeanFactory.class.isAssignableFrom(beanClass)) {
            if (beanFactoryBeanId == null) {
                beanFactoryBeanId = beanName;
            } else {
                throw new FatalBeanException(
                        "Duplicated org.bytesoft.compensable.CompensableBeanFactory defined.");
            }
        } else if (CompensableMethodInterceptor.class.equals(beanClass)) {
            if (interceptorBeanId == null) {
                interceptorBeanId = beanName;
            } else {
                throw new IllegalStateException(
                        "Duplicated org.bytesoft.bytetcc.supports.spring.CompensableMethodInterceptor defined.");
            }
        }

    }

    if (beanFactoryBeanId == null) {
        throw new IllegalStateException(
                "No configuration of class org.bytesoft.compensable.CompensableBeanFactory was found.");
    }
    if (interceptorBeanId == null) {
        throw new IllegalStateException(
                "No configuration of class org.bytesoft.bytetcc.supports.spring.CompensableMethodInterceptor was found.");
    }

    for (int i = 0; i < beanFactoryAwareBeanIdList.size(); i++) {
        BeanDefinition beanDef = beanFactoryAwareBeanIdList.get(i);
        MutablePropertyValues mpv = beanDef.getPropertyValues();
        RuntimeBeanReference beanRef = new RuntimeBeanReference(beanFactoryBeanId);
        mpv.addPropertyValue(CompensableBeanFactoryAware.BEAN_FACTORY_FIELD_NAME, beanRef);
    }

    BeanDefinition beanDef = beanFactory.getBeanDefinition(beanFactoryBeanId);
    MutablePropertyValues mpv = beanDef.getPropertyValues();
    RuntimeBeanReference synchronization = new RuntimeBeanReference(interceptorBeanId);
    mpv.addPropertyValue("compensableSynchronization", synchronization);
}