List of usage examples for java.lang ClassLoader loadClass
public Class<?> loadClass(String name) throws ClassNotFoundException
From source file:com.gigaspaces.internal.utils.ClassLoaderCleaner.java
/** * Clear references./*from w w w. j a v a 2 s . c om*/ */ public static void clearReferences(ClassLoader classLoader) { ClassLoaderCache.getCache().removeClassLoader(classLoader); if (NonActivatableServiceDescriptor.getGlobalPolicy() != null) { NonActivatableServiceDescriptor.getGlobalPolicy().setPolicy(classLoader, null); } // De-register any remaining JDBC drivers clearReferencesJdbc(classLoader); // Stop any threads the web application started clearReferencesThreads(classLoader); // Clear any ThreadLocals loaded by this class loader clearReferencesThreadLocals(classLoader); // Clear RMI Targets loaded by this class loader clearReferencesRmiTargets(classLoader); clearRmiLoaderHandler(classLoader); // Clear the classloader reference in common-logging try { Class clazz = classLoader.loadClass("org.apache.commons.logging.LogFactory"); clazz.getMethod("release", ClassLoader.class).invoke(null, classLoader); } catch (Throwable t) { // ignore } try { Class clazz = classLoader.loadClass("org.apache.juli.logging.LogFactory"); clazz.getMethod("release", ClassLoader.class).invoke(null, classLoader); } catch (Throwable t) { // ignore } // Clear the resource bundle cache // This shouldn't be necessary, the cache uses weak references but // it has caused leaks. Oddly, using the leak detection code in // standard host allows the class loader to be GC'd. This has been seen // on Sun but not IBM JREs. Maybe a bug in Sun's GC impl? clearReferencesResourceBundles(classLoader); // Clear the classloader reference in the VM's bean introspector java.beans.Introspector.flushCaches(); }
From source file:com.dianping.resource.io.util.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//from w ww . j a va2 s. c om * @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 { 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('.'); if (lastDotIndex != -1) { String innerClassName = name.substring(0, lastDotIndex) + '$' + 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 public void simpleTypesInExampleAreMappedToCorrectJavaTypes() throws Exception { ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/json/simpleTypes.json", "com.example", config("sourceType", "json")); Class<?> generatedType = resultsClassLoader.loadClass("com.example.SimpleTypes"); Object deserialisedValue = OBJECT_MAPPER .readValue(this.getClass().getResourceAsStream("/json/simpleTypes.json"), generatedType); assertThat((String) generatedType.getMethod("getA").invoke(deserialisedValue), is("abc")); assertThat((Integer) generatedType.getMethod("getB").invoke(deserialisedValue), is(123)); assertThat((Double) generatedType.getMethod("getC").invoke(deserialisedValue), is(12999999999999999999999.99d)); assertThat((Boolean) generatedType.getMethod("getD").invoke(deserialisedValue), is(true)); assertThat(generatedType.getMethod("getE").invoke(deserialisedValue), is(nullValue())); }
From source file:org.jsonschema2pojo.integration.JavaNameIT.java
@Test public void gettersHaveCorrectNames() throws NoSuchMethodException, IllegalAccessException, InstantiationException, ClassNotFoundException { ClassLoader javaNameClassLoader = schemaRule.generateAndCompile("/schema/javaName/javaName.json", "com.example.javaname"); Class<?> classWithJavaNames = javaNameClassLoader.loadClass("com.example.javaname.JavaName"); classWithJavaNames.getMethod("getJavaProperty"); classWithJavaNames.getMethod("getPropertyWithoutJavaName"); classWithJavaNames.getMethod("getJavaEnum"); classWithJavaNames.getMethod("getEnumWithoutJavaName"); classWithJavaNames.getMethod("getJavaObject"); classWithJavaNames.getMethod("getObjectWithoutJavaName"); }
From source file:org.opentaps.common.reporting.ChartViewHandler.java
public void render(String name, String page, String info, String contentType, String encoding, HttpServletRequest request, HttpServletResponse response) throws ViewHandlerException { /*//from www. java 2s .c om * Looks for parameter "chart" first. Send this temporary image files * to client if it exists and return. */ String chartFileName = UtilCommon.getParameter(request, "chart"); if (UtilValidate.isNotEmpty(chartFileName)) { try { ServletUtilities.sendTempFile(chartFileName, response); if (chartFileName.indexOf(ServletUtilities.getTempOneTimeFilePrefix()) != -1) { // delete temporary file File file = new File(System.getProperty("java.io.tmpdir"), chartFileName); file.delete(); } } catch (IOException ioe) { Debug.logError(ioe.getLocalizedMessage(), module); } return; } /* * Next option eliminate need to store chart in file system. Some event handler * included in request chain prior to this view handler can prepare ready to use * instance of JFreeChart and place it to request attribute chartContext. * Currently chartContext should be Map<String, Object> and we expect to see in it: * "charObject" : JFreeChart * "width" : positive Integer * "height" : positive Integer * "encodeAlpha" : Boolean (optional) * "compressRatio" : Integer in range 0-9 (optional) */ Map<String, Object> chartContext = (Map<String, Object>) request.getAttribute("chartContext"); if (UtilValidate.isNotEmpty(chartContext)) { try { sendChart(chartContext, response); } catch (IOException ioe) { Debug.logError(ioe.getLocalizedMessage(), module); } return; } /* * Prepare context for next options */ Map<String, Object> callContext = FastMap.newInstance(); callContext.put("parameters", UtilHttp.getParameterMap(request)); callContext.put("delegator", request.getAttribute("delegator")); callContext.put("dispatcher", request.getAttribute("dispatcher")); callContext.put("userLogin", request.getSession().getAttribute("userLogin")); callContext.put("locale", UtilHttp.getLocale(request)); /* * view-map attribute "page" may contain BeanShell script in component * URL format that should return chartContext map. */ if (UtilValidate.isNotEmpty(page) && UtilValidate.isUrl(page) && page.endsWith(".bsh")) { try { chartContext = (Map<String, Object>) BshUtil.runBshAtLocation(page, callContext); if (UtilValidate.isNotEmpty(chartContext)) { sendChart(chartContext, response); } } catch (GeneralException ge) { Debug.logError(ge.getLocalizedMessage(), module); } catch (IOException ioe) { Debug.logError(ioe.getLocalizedMessage(), module); } return; } /* * As last resort we can decide that "page" attribute contains class name and "info" * contains method Map<String, Object> getSomeChart(Map<String, Object> context). * There are parameters, delegator, dispatcher, userLogin and locale in the context. * Should return chartContext. */ if (UtilValidate.isNotEmpty(page) && UtilValidate.isNotEmpty(info)) { Class handler = null; synchronized (this) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); try { handler = loader.loadClass(page); if (handler != null) { Method runMethod = handler.getMethod(info, new Class[] { Map.class }); chartContext = (Map<String, Object>) runMethod.invoke(null, callContext); if (UtilValidate.isNotEmpty(chartContext)) { sendChart(chartContext, response); } } } catch (ClassNotFoundException cnfe) { Debug.logError(cnfe.getLocalizedMessage(), module); } catch (SecurityException se) { Debug.logError(se.getLocalizedMessage(), module); } catch (NoSuchMethodException nsme) { Debug.logError(nsme.getLocalizedMessage(), module); } catch (IllegalArgumentException iae) { Debug.logError(iae.getLocalizedMessage(), module); } catch (IllegalAccessException iace) { Debug.logError(iace.getLocalizedMessage(), module); } catch (InvocationTargetException ite) { Debug.logError(ite.getLocalizedMessage(), module); } catch (IOException ioe) { Debug.logError(ioe.getLocalizedMessage(), module); } } } // Why you disturb me? throw new ViewHandlerException( "In order to generate chart you have to provide chart object or file name. There are no such data in request. Please read comments to ChartViewHandler class."); }
From source file:org.jsonschema2pojo.integration.JavaNameIT.java
@Test public void propertiesHaveCorrectNames() throws IllegalAccessException, InstantiationException, ClassNotFoundException { ClassLoader javaNameClassLoader = schemaRule.generateAndCompile("/schema/javaName/javaName.json", "com.example.javaname"); Class<?> classWithJavaNames = javaNameClassLoader.loadClass("com.example.javaname.JavaName"); Object instance = classWithJavaNames.newInstance(); assertThat(instance, hasProperty("javaProperty")); assertThat(instance, hasProperty("propertyWithoutJavaName")); assertThat(instance, hasProperty("javaEnum")); assertThat(instance, hasProperty("enumWithoutJavaName")); assertThat(instance, hasProperty("javaObject")); assertThat(instance, hasProperty("objectWithoutJavaName")); }
From source file:org.jsonschema2pojo.integration.JavaNameIT.java
@Test public void propertiesHaveCorrectTypes() throws IllegalAccessException, InstantiationException, ClassNotFoundException, NoSuchFieldException, IntrospectionException { ClassLoader javaNameClassLoader = schemaRule.generateAndCompile("/schema/javaName/javaName.json", "com.example.javaname"); Class<?> classWithJavaNames = javaNameClassLoader.loadClass("com.example.javaname.JavaName"); Object instance = classWithJavaNames.newInstance(); assertThat(classWithJavaNames.getDeclaredField("javaEnum").getType(), typeCompatibleWith(javaNameClassLoader.loadClass("com.example.javaname.JavaName$JavaEnum"))); assertThat(classWithJavaNames.getDeclaredField("enumWithoutJavaName").getType(), typeCompatibleWith( javaNameClassLoader.loadClass("com.example.javaname.JavaName$EnumWithoutJavaName"))); assertThat(classWithJavaNames.getDeclaredField("javaObject").getType(), typeCompatibleWith(javaNameClassLoader.loadClass("com.example.javaname.JavaObject"))); assertThat(classWithJavaNames.getDeclaredField("objectWithoutJavaName").getType(), typeCompatibleWith(javaNameClassLoader.loadClass("com.example.javaname.ObjectWithoutJavaName"))); }
From source file:org.jsonschema2pojo.integration.JavaNameIT.java
@Test public void serializedPropertiesHaveCorrectNames() throws IllegalAccessException, InstantiationException, IntrospectionException, InvocationTargetException, ClassNotFoundException { ClassLoader javaNameClassLoader = schemaRule.generateAndCompile("/schema/javaName/javaName.json", "com.example.javaname"); Class<?> classWithJavaNames = javaNameClassLoader.loadClass("com.example.javaname.JavaName"); Object instance = classWithJavaNames.newInstance(); new PropertyDescriptor("javaProperty", classWithJavaNames).getWriteMethod().invoke(instance, "abc"); new PropertyDescriptor("propertyWithoutJavaName", classWithJavaNames).getWriteMethod().invoke(instance, "abc"); JsonNode serialized = mapper.valueToTree(instance); assertThat(serialized.has("propertyWithJavaName"), is(true)); assertThat(serialized.has("propertyWithoutJavaName"), is(true)); }
From source file:com.google.gdt.eclipse.designer.uibinder.parser.UiBinderRenderer.java
/** * Implementation of {@link #render()}./* ww w .j av a 2 s . co m*/ */ private void render0() throws Exception { GlobalStateXml.activate(m_rootModel); fillMap_pathToModel(); // load Binder Object createdBinder; { ClassLoader classLoader = m_context.getClassLoader(); String binderClassName = m_context.getBinderClassName(); m_context.getState().getDevModeBridge().invalidateRebind(binderClassName); Class<?> binderClass = classLoader.loadClass(binderClassName); Class<?> classGWT = classLoader.loadClass("com.google.gwt.core.client.GWT"); createdBinder = ReflectionUtils.invokeMethod(classGWT, "create(java.lang.Class)", binderClass); setObjects(createdBinder); } // render Widget(s) ReflectionUtils.invokeMethod(createdBinder, "createAndBindUi(java.lang.Object)", (Object) null); setAttributes(createdBinder); }
From source file:org.jsonschema2pojo.integration.json.JsonTypesIT.java
@Test public void arrayItemsAreNotRecursivelyMerged() throws Exception { ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/json/simplePropertiesInArrayItem.json", "com.example", config("sourceType", "json")); Class<?> genType = resultsClassLoader.loadClass("com.example.SimplePropertiesInArrayItem"); // Different array items use different types for the same property; // we don't support union types, so we have to pick one assertEquals(Integer.class, genType.getMethod("getScalar").getReturnType()); thrown.expect(InvalidFormatException.class); thrown.expectMessage("Can not construct instance of java.lang.Integer from String value (\"what\")"); OBJECT_MAPPER.readValue(this.getClass().getResourceAsStream("/json/simplePropertiesInArrayItem.json"), Array.newInstance(genType, 0).getClass()); }