List of usage examples for java.lang ClassLoader loadClass
public Class<?> loadClass(String name) throws ClassNotFoundException
From source file:org.paxml.util.ReflectUtils.java
/** * Load a class, converting possible ClassNotFoundException into * paxmlRuntimeException./*from www. j a v a 2 s . c o m*/ * * @param className * the class name * @param cl * the classloader, set to null to use the current thread context * class loader. * @return the loaded class. * @throws PaxmlRuntimeException * if the load fails. */ public static Class<?> loadClassStrict(String className, ClassLoader cl) { cl = cl == null ? Thread.currentThread().getContextClassLoader() : cl; try { return cl.loadClass(className); } catch (ClassNotFoundException e) { throw new PaxmlRuntimeException("Class not found: " + className, e); } }
From source file:com.cenrise.test.azkaban.Utils.java
public static Object invokeStaticMethod(final ClassLoader loader, final String className, final String methodName, final Object... args) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { final Class<?> clazz = loader.loadClass(className); final Class<?>[] argTypes = new Class[args.length]; for (int i = 0; i < args.length; ++i) { // argTypes[i] = args[i].getClass(); argTypes[i] = args[i].getClass(); }/* ww w .j a v a 2 s. c o m*/ final Method method = clazz.getDeclaredMethod(methodName, argTypes); return method.invoke(null, args); }
From source file:edu.uci.ics.asterix.metadata.feeds.FeedUtil.java
public static Triple<IFeedAdapterFactory, ARecordType, AdapterType> getPrimaryFeedFactoryAndOutput( PrimaryFeed feed, FeedPolicyAccessor policyAccessor, MetadataTransactionContext mdTxnCtx) throws AlgebricksException { String adapterName = null;//from w w w . j a va2 s . c om DatasourceAdapter adapterEntity = null; String adapterFactoryClassname = null; IFeedAdapterFactory adapterFactory = null; ARecordType adapterOutputType = null; Triple<IFeedAdapterFactory, ARecordType, AdapterType> feedProps = null; AdapterType adapterType = null; try { adapterName = feed.getAdaptorName(); adapterEntity = MetadataManager.INSTANCE.getAdapter(mdTxnCtx, MetadataConstants.METADATA_DATAVERSE_NAME, adapterName); if (adapterEntity == null) { adapterEntity = MetadataManager.INSTANCE.getAdapter(mdTxnCtx, feed.getDataverseName(), adapterName); } if (adapterEntity != null) { adapterType = adapterEntity.getType(); adapterFactoryClassname = adapterEntity.getClassname(); switch (adapterType) { case INTERNAL: adapterFactory = (IFeedAdapterFactory) Class.forName(adapterFactoryClassname).newInstance(); break; case EXTERNAL: String[] anameComponents = adapterName.split("#"); String libraryName = anameComponents[0]; ClassLoader cl = ExternalLibraryManager.getLibraryClassLoader(feed.getDataverseName(), libraryName); adapterFactory = (IFeedAdapterFactory) cl.loadClass(adapterFactoryClassname).newInstance(); break; } } else { adapterFactoryClassname = AqlMetadataProvider.adapterFactoryMapping.get(adapterName); if (adapterFactoryClassname == null) { adapterFactoryClassname = adapterName; } adapterFactory = (IFeedAdapterFactory) Class.forName(adapterFactoryClassname).newInstance(); adapterType = AdapterType.INTERNAL; } Map<String, String> configuration = feed.getAdaptorConfiguration(); configuration.putAll(policyAccessor.getFeedPolicy()); adapterOutputType = getOutputType(feed, configuration); adapterFactory.configure(configuration, adapterOutputType); feedProps = new Triple<IFeedAdapterFactory, ARecordType, AdapterType>(adapterFactory, adapterOutputType, adapterType); } catch (Exception e) { e.printStackTrace(); throw new AlgebricksException("unable to create adapter " + e); } return feedProps; }
From source file:com.legstar.protobuf.cobol.ProtoCobol.java
/** * Rather than using the Class.forName mechanism first, this uses * Thread.getContextClassLoader instead. In a Servlet context such as * Tomcat, this allows JAXB classes for instance to be loaded from the web * application (webapp) location while this code might have been loaded from * shared/lib. If Thread.getContextClassLoader fails to locate the class * then we give a last chance to Class.forName. * //from w w w. j ava 2 s.com * @param qualifiedClassName the class name to load * @return the class * @throws ClassNotFoundException if class is not accessible from any class * loader */ public static Class<?> loadClass(final String qualifiedClassName) throws ClassNotFoundException { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); if (contextClassLoader == null) { return Class.forName(qualifiedClassName); } try { return contextClassLoader.loadClass(qualifiedClassName); } catch (ClassNotFoundException e) { return Class.forName(qualifiedClassName); } }
From source file:com.gigaspaces.internal.utils.ClassLoaderCleaner.java
private static void clearRmiLoaderHandler(ClassLoader classLoader) { // HACK: Clear it from the RMI class loader as well // We can safely remove this since we no longer have this class loader around // and the table key is based on the class loader try {//from ww w. j a v a 2 s . c om final Class<?> loaderHandlerClass = classLoader.loadClass("sun.rmi.server.LoaderHandler"); synchronized (loaderHandlerClass) { Field loadTableField = loaderHandlerClass.getDeclaredField("loaderTable"); loadTableField.setAccessible(true); Map<?, ?> loaderTable = (Map<?, ?>) loadTableField.get(null); for (Iterator it = loaderTable.entrySet().iterator(); it.hasNext();) { Map.Entry<?, ?> entry = (Map.Entry<?, ?>) it.next(); Object loaderKey = entry.getKey(); Field parentField = loaderKey.getClass().getDeclaredField("parent"); parentField.setAccessible(true); if (parentField.get(loaderKey) == classLoader) { it.remove(); } } } } catch (Throwable t) { // ignore } }
From source file:com.citytechinc.cq.component.touchuidialog.util.TouchUIDialogUtil.java
public static List<TouchUIWidgetMakerParameters> getWidgetMakerParametersForComponentClass( CtClass componentClass, ClassLoader classLoader, ClassPool classPool, TouchUIWidgetRegistry widgetRegistry) throws NotFoundException, ClassNotFoundException, InvalidComponentClassException { List<TouchUIWidgetMakerParameters> widgetMakerParametersList = new ArrayList<TouchUIWidgetMakerParameters>(); List<CtMember> fieldsAndMethods = new ArrayList<CtMember>(); fieldsAndMethods.addAll(ComponentMojoUtil.collectFields(componentClass)); fieldsAndMethods.addAll(ComponentMojoUtil.collectMethods(componentClass)); // Load the true class Class<?> trueComponentClass = classLoader.loadClass(componentClass.getName()); // Iterate through all the fields creating configs for each and // preparing the necessary widget maker parameters for (CtMember member : fieldsAndMethods) { if (!member.hasAnnotation(IgnoreDialogField.class)) { DialogFieldConfig dialogFieldConfig = null; if (member instanceof CtMethod) { dialogFieldConfig = DialogUtil.getDialogFieldFromSuperClasses((CtMethod) member); } else { if (member.hasAnnotation(DialogField.class)) { dialogFieldConfig = new DialogFieldConfig( (DialogField) member.getAnnotation(DialogField.class), member); }/*from w w w.jav a 2 s. c o m*/ } if (dialogFieldConfig != null && !dialogFieldConfig.isSuppressTouchUI()) { TouchUIWidgetMakerParameters touchUIWidgetMakerParameters = new TouchUIWidgetMakerParameters(); touchUIWidgetMakerParameters.setClassLoader(classLoader); touchUIWidgetMakerParameters.setContainingClass(trueComponentClass); touchUIWidgetMakerParameters.setDialogFieldConfig(dialogFieldConfig); touchUIWidgetMakerParameters.setClassPool(classPool); touchUIWidgetMakerParameters.setUseDotSlashInName(true); touchUIWidgetMakerParameters.setWidgetRegistry(widgetRegistry); widgetMakerParametersList.add(touchUIWidgetMakerParameters); } } } return widgetMakerParametersList; }
From source file:com.acciente.induction.init.ViewResolverInitializer.java
public static ViewResolver getViewResolver(Config.ViewResolver oViewResolverConfig, Config.ViewMapping oViewMappingConfig, ModelPool oModelPool, ClassLoader oClassLoader, ServletConfig oServletConfig)/*from w w w . jav a 2 s . co m*/ throws ClassNotFoundException, InvocationTargetException, ConstructorNotFoundException, ParameterProviderException, IllegalAccessException, InstantiationException, IOException { ViewResolver oViewResolver; String sViewResolverClassName; Log oLog; oLog = LogFactory.getLog(ViewResolverInitializer.class); sViewResolverClassName = oViewResolverConfig.getClassName(); if (Strings.isEmpty(sViewResolverClassName)) { oViewResolver = new ShortURLViewResolver(oViewMappingConfig, oClassLoader); } else { oLog.info("loading user-defined view resolver: " + sViewResolverClassName); Class oViewResolverClass = oClassLoader.loadClass(sViewResolverClassName); // attempt to find and call the single public constructor oViewResolver = (ViewResolver) ObjectFactory.createObject(oViewResolverClass, new Object[] { oServletConfig, oViewResolverConfig, oViewMappingConfig, oClassLoader }, new InitializerParameterProvider(oModelPool, "view-resolver-init")); } return oViewResolver; }
From source file:io.github.tavernaextras.biocatalogue.model.Util.java
/** * This method is "clones" an object supplied as an argument. It uses * serialisation to achieve this (as opposed to manually implementing deep * copying of all referenced objects in the graph of the provided object). * This technique is used to make sure that the new object will be exact * replica, but totally independent of the original one. * //from w w w . j a v a 2s .co m * Note that this code works ~100 times slower than it would do if deep copying * was implemented. However, this will not be used in tight loops (and in loops * at all), so for one-off tasks it is fine. * * @author Dave Miller<br/> * Original version of the code in this method is taken from * <a href="http://www.javaworld.com/javaworld/javatips/jw-javatip76.html?page=2"> * http://www.javaworld.com/javaworld/javatips/jw-javatip76.html?page=2 * </a> [accessed on 25/Feb/2010]. * <br/><br/> * * @author Subhajit Dasgupta<br/> * Example of using an alternative class loader during object de-serialisation * was taken from * <a href="http://blogs.sun.com/adventures/entry/desrializing_objects_custom_class_loaders"> * http://blogs.sun.com/adventures/entry/desrializing_objects_custom_class_loaders * </a> [accessed on 29/Mar/2010]. * * @return Deep copy of the provided object. If deep copying doesn't succeed, * <code>null</code> is returned. */ public static Object deepCopy(Object objectToCopy) { // a "safety net" - a class loader of BioCatalogue perspective may be used in // de-serialisation process to make sure that all classes are recognised // (system class loader may not be able to "see" all BioCatalogue plugin's files, // but just those in Taverna's /lib folder) final ClassLoader[] customClassLoaders = new ClassLoader[] { BioCataloguePerspective.class.getClassLoader() }; try { ObjectOutputStream oos = null; ObjectInputStream ois = null; try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(bos); // serialise and pass the object oos.writeObject(objectToCopy); oos.flush(); // read and return the new object ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray()); ois = new ObjectInputStream(bin) { /** * <code>resolveClass()</code> method is overridden to make use of * custom ClassLoader in the de-serialisation process. * <br/> * This is needed to make sure that the ClassLoader of the BioCatalogue * perspective is used as opposed to the system ClassLoader which will * only be able to see classes from Taverna's /lib folder. */ protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { String className = desc.getName(); try { // attempt to use default class loader return Class.forName(className); } catch (ClassNotFoundException exc) { // default class loader was unable to locate a required class - // attempt to use one of the provided class loaders for (ClassLoader cl : customClassLoaders) { try { return cl.loadClass(className); } catch (ClassNotFoundException e) { /* do nothing here - there may be other class loaders to try */ } } // none of the class loaders was able to recognise the currently // de-serialised class, so it's indeed an exception throw new ClassNotFoundException(className + " -- neither system, nor alternative class loaders were able to load this class"); } } }; return ois.readObject(); } catch (Exception e) { logger.error("Could not perform deep copy of " + objectToCopy.getClass() + " instance", e); } finally { oos.close(); ois.close(); } } catch (Exception e) { logger.error( "Could not close object streams during deep copy of " + objectToCopy.getClass() + " instance"); } // Error occurred - couldn't produce the deep copy... return null; }
From source file:com.acciente.induction.init.RedirectResolverInitializer.java
public static RedirectResolver getRedirectResolver(Config.RedirectResolver oRedirectResolverConfig, Config.RedirectMapping oRedirectMappingConfig, ModelPool oModelPool, ClassLoader oClassLoader, ServletConfig oServletConfig)/*w w w . j av a 2s .co m*/ throws ClassNotFoundException, InvocationTargetException, ConstructorNotFoundException, ParameterProviderException, IllegalAccessException, InstantiationException, IOException { RedirectResolver oRedirectResolver; String sRedirectResolverClassName; Log oLog; oLog = LogFactory.getLog(RedirectResolverInitializer.class); sRedirectResolverClassName = oRedirectResolverConfig.getClassName(); if (Strings.isEmpty(sRedirectResolverClassName)) { oRedirectResolver = new ShortURLRedirectResolver(oRedirectMappingConfig, oClassLoader); } else { oLog.info("loading user-defined redirect resolver: " + sRedirectResolverClassName); Class oRedirectResolverClass = oClassLoader.loadClass(sRedirectResolverClassName); // attempt to find and call the single public constructor oRedirectResolver = (RedirectResolver) ObjectFactory.createObject(oRedirectResolverClass, new Object[] { oServletConfig, oRedirectResolverConfig, oRedirectMappingConfig, oClassLoader }, new InitializerParameterProvider(oModelPool, "redirect-resolver-init")); } return oRedirectResolver; }
From source file:ch.entwine.weblounge.common.impl.scheduler.QuartzJob.java
/** * Initializes this job from an XML node that was generated using * {@link #toXml()}./*from ww w. j a v a2s .c o m*/ * * @param context * the job node * @param xpathProcessor * xpath processor to use * @throws IllegalStateException * if the job cannot be parsed * @see #toXml() */ @SuppressWarnings("unchecked") public static Job fromXml(Node config, XPath xPathProcessor) throws IllegalStateException { CronJobTrigger jobTrigger = null; Dictionary<String, Object> ctx = new Hashtable<String, Object>(); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // Main attributes String identifier = XPathHelper.valueOf(config, "@id", xPathProcessor); // Implementation class String className = XPathHelper.valueOf(config, "m:class", xPathProcessor); Class<? extends JobWorker> c; try { c = (Class<? extends JobWorker>) classLoader.loadClass(className); c.newInstance(); // Create an instance just to make sure we catch any errors right here } catch (ClassNotFoundException e) { throw new IllegalStateException( "Implementation " + className + " for job '" + identifier + "' not found", e); } catch (InstantiationException e) { throw new IllegalStateException( "Error instantiating impelementation " + className + " for job '" + identifier + "'", e); } catch (IllegalAccessException e) { throw new IllegalStateException( "Access violation instantiating implementation " + className + " for job '" + identifier + "'", e); } catch (Throwable t) { throw new IllegalStateException( "Error loading implementation " + className + " for job '" + identifier + "'", t); } // Read execution schedule String schedule = XPathHelper.valueOf(config, "m:schedule", xPathProcessor); if (schedule == null) throw new IllegalStateException("No schedule has been defined for job '" + identifier + "'"); jobTrigger = new CronJobTrigger(schedule); // Read options Node nodes = XPathHelper.select(config, "m:options", xPathProcessor); OptionsHelper options = OptionsHelper.fromXml(nodes, xPathProcessor); for (Map.Entry<String, Map<Environment, List<String>>> entry : options.getOptions().entrySet()) { String key = entry.getKey(); Map<Environment, List<String>> environments = entry.getValue(); for (Environment environment : environments.keySet()) { List<String> values = environments.get(environment); if (values.size() == 1) ctx.put(key, values.get(0)); else ctx.put(key, values.toArray(new String[values.size()])); } } // Did we find something? QuartzJob job = new QuartzJob(identifier, c, ctx, jobTrigger); job.options = options; // name String name = XPathHelper.valueOf(config, "m:name", xPathProcessor); job.setName(name); return job; }