List of usage examples for java.lang ClassLoader loadClass
public Class<?> loadClass(String name) throws ClassNotFoundException
From source file:com.googlecode.psiprobe.tools.logging.slf4jlogback.TomcatSlf4jLogbackFactoryAccessor.java
/** * Attempts to initialize a TomcatSlf4jLogback logger factory via the given class loader. * /* ww w .j a va 2 s. com*/ * @param cl the ClassLoader to use when fetching the factory */ public TomcatSlf4jLogbackFactoryAccessor(ClassLoader cl) throws ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { // Get the singleton SLF4J binding, which may or may not be Logback, depending on the binding. Class clazz = cl.loadClass("org.apache.juli.logging.org.slf4j.impl.StaticLoggerBinder"); Method getSingleton = MethodUtils.getAccessibleMethod(clazz, "getSingleton", new Class[] {}); Object singleton = getSingleton.invoke(null, null); Method getLoggerFactory = MethodUtils.getAccessibleMethod(clazz, "getLoggerFactory", new Class[] {}); Object loggerFactory = getLoggerFactory.invoke(singleton, null); // Check if the binding is indeed Logback Class loggerFactoryClass = cl.loadClass("org.apache.juli.logging.ch.qos.logback.classic.LoggerContext"); if (!loggerFactoryClass.isInstance(loggerFactory)) { throw new RuntimeException("The singleton SLF4J binding was not Logback"); } setTarget(loggerFactory); }
From source file:com.googlecode.jsonschema2pojo.integration.AdditionalPropertiesIT.java
@Test public void additionalPropertiesOfStringArrayTypeOnly() throws SecurityException, NoSuchMethodException, ClassNotFoundException { ClassLoader resultsClassLoader = generateAndCompile( "/schema/additionalProperties/additionalPropertiesArraysOfStrings.json", "com.example"); Class<?> classWithNoAdditionalProperties = resultsClassLoader .loadClass("com.example.AdditionalPropertiesArraysOfStrings"); Method getter = classWithNoAdditionalProperties.getMethod("getAdditionalProperties"); ParameterizedType listType = (ParameterizedType) ((ParameterizedType) getter.getGenericReturnType()) .getActualTypeArguments()[1]; assertThat(listType.getActualTypeArguments()[0], is(equalTo((Type) String.class))); // setter with these types should exist: classWithNoAdditionalProperties.getMethod("setAdditionalProperties", String.class, List.class); }
From source file:com.sillelien.dollar.DocTestingVisitor.java
@Override public void visit(@NotNull VerbatimNode node) { if ("java".equals(node.getType())) { try {// w ww . ja v a 2 s . c o m String name = "DocTemp" + System.currentTimeMillis(); File javaFile = new File("/tmp/" + name + ".java"); File clazzFile = new File("/tmp/" + name + ".class"); clazzFile.getParentFile().mkdirs(); FileUtils.write(javaFile, "import com.sillelien.dollar.api.*;\n" + "import static com.sillelien.dollar.api.DollarStatic.*;\n" + "public class " + name + " implements java.lang.Runnable{\n" + " public void run() {\n" + " " + node.getText() + "\n" + " }\n" + "}"); final JavaCompiler javac = ToolProvider.getSystemJavaCompiler(); final StandardJavaFileManager jfm = javac.getStandardFileManager(null, null, null); JavaCompiler.CompilationTask task; DiagnosticListener<JavaFileObject> diagnosticListener = new DiagnosticListener<JavaFileObject>() { @Override public void report(Diagnostic diagnostic) { System.out.println(diagnostic); throw new RuntimeException(diagnostic.getMessage(Locale.getDefault())); } }; try (FileOutputStream fileOutputStream = FileUtils.openOutputStream(clazzFile)) { task = javac.getTask(new OutputStreamWriter(fileOutputStream), jfm, diagnosticListener, null, null, jfm.getJavaFileObjects(javaFile)); } task.call(); try { // Convert File to a URL URL url = clazzFile.getParentFile().toURL(); URL[] urls = new URL[] { url }; ClassLoader cl = new URLClassLoader(urls); Class cls = cl.loadClass(name); ((Runnable) cls.newInstance()).run(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } System.out.println("Parsed: " + node.getText()); } catch (IOException e) { throw new RuntimeException(e); } } }
From source file:be.fedict.eid.idp.model.bean.ProtocolServiceManagerBean.java
public IdentityProviderProtocolService getProtocolService( IdentityProviderProtocolType identityProviderProtocol) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); LOG.debug("loading protocol service class: " + identityProviderProtocol.getProtocolService()); Class<?> protocolServiceClass; try {//w w w. jav a 2s . c o m protocolServiceClass = classLoader.loadClass(identityProviderProtocol.getProtocolService()); } catch (ClassNotFoundException e) { LOG.error("protocol service class not found: " + identityProviderProtocol.getProtocolService(), e); return null; } if (!IdentityProviderProtocolService.class.isAssignableFrom(protocolServiceClass)) { LOG.error("illegal protocol service class: " + identityProviderProtocol.getProtocolService()); return null; } IdentityProviderProtocolService protocolService; try { protocolService = (IdentityProviderProtocolService) protocolServiceClass.newInstance(); } catch (Exception e) { LOG.error("could not init the protocol service object: " + e.getMessage(), e); return null; } return protocolService; }
From source file:be.fedict.eid.idp.model.bean.AttributeServiceManagerBean.java
public IdentityProviderAttributeService getAttributeService( IdentityProviderAttributeType identityProviderAttribute) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); LOG.debug("loading attribute service class: " + identityProviderAttribute.getAttributeService()); Class<?> attributeServiceClass; try {/*from w w w. j a v a 2 s . c o m*/ attributeServiceClass = classLoader.loadClass(identityProviderAttribute.getAttributeService()); } catch (ClassNotFoundException e) { LOG.error("attribute service class not found: " + identityProviderAttribute.getAttributeService(), e); return null; } if (!IdentityProviderAttributeService.class.isAssignableFrom(attributeServiceClass)) { LOG.error("illegal attribute service class: " + identityProviderAttribute.getAttributeService()); return null; } IdentityProviderAttributeService attributeService; try { attributeService = (IdentityProviderAttributeService) attributeServiceClass.newInstance(); } catch (Exception e) { LOG.error("could not init the attribute service object: " + e.getMessage(), e); return null; } return attributeService; }
From source file:org.jsonschema2pojo.integration.PropertiesIT.java
@Test @SuppressWarnings("rawtypes") public void usePrimitivesArgumentCausesPrimitiveTypes() throws ClassNotFoundException, IntrospectionException, InstantiationException, IllegalAccessException, InvocationTargetException { ClassLoader resultsClassLoader = schemaRule.generateAndCompile( "/schema/properties/primitiveProperties.json", "com.example", config("usePrimitives", true)); Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties"); assertThat(new PropertyDescriptor("a", generatedType).getReadMethod().getReturnType().getName(), is("int")); assertThat(new PropertyDescriptor("b", generatedType).getReadMethod().getReturnType().getName(), is("double")); assertThat(new PropertyDescriptor("c", generatedType).getReadMethod().getReturnType().getName(), is("boolean")); }
From source file:com.googlecode.jsonschema2pojo.integration.PropertiesIT.java
@Test @SuppressWarnings("rawtypes") public void wordDelimitersCausesCamelCase() throws ClassNotFoundException, IntrospectionException, InstantiationException, IllegalAccessException, InvocationTargetException { ClassLoader resultsClassLoader = generateAndCompile("/schema/properties/propertiesWithWordDelimiters.json", "com.example", config("usePrimitives", true, "propertyWordDelimiters", "_ -")); Class generatedType = resultsClassLoader.loadClass("com.example.WordDelimit"); Object instance = generatedType.newInstance(); new PropertyDescriptor("propertyWithUnderscores", generatedType).getWriteMethod().invoke(instance, "a_b_c"); new PropertyDescriptor("propertyWithHyphens", generatedType).getWriteMethod().invoke(instance, "a-b-c"); new PropertyDescriptor("propertyWithMixedDelimiters", generatedType).getWriteMethod().invoke(instance, "a b_c-d"); JsonNode jsonified = mapper.valueToTree(instance); assertThat(jsonified.has("property_with_underscores"), is(true)); assertThat(jsonified.has("property-with-hyphens"), is(true)); assertThat(jsonified.has("property_with mixed-delimiters"), is(true)); }
From source file:com.googlecode.psiprobe.tools.logging.logback.LogbackFactoryAccessor.java
/** * Attempts to initialize a Logback logger factory via the given class loader. * /*from ww w . ja va 2 s . c o m*/ * @param cl the ClassLoader to use when fetching the factory */ public LogbackFactoryAccessor(ClassLoader cl) throws ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { // Get the singleton SLF4J binding, which may or may not be Logback, depending on the // binding. Class clazz = cl.loadClass("org.slf4j.impl.StaticLoggerBinder"); Method m1 = MethodUtils.getAccessibleMethod(clazz, "getSingleton", new Class[] {}); Object singleton = m1.invoke(null, null); Method m = MethodUtils.getAccessibleMethod(clazz, "getLoggerFactory", new Class[] {}); Object loggerFactory = m.invoke(singleton, null); // Check if the binding is indeed Logback Class loggerFactoryClass = cl.loadClass("ch.qos.logback.classic.LoggerContext"); if (!loggerFactoryClass.isInstance(loggerFactory)) { throw new RuntimeException("The singleton SLF4J binding was not Logback"); } setTarget(loggerFactory); }
From source file:net.morematerials.manager.HandlerManager.java
public void load(File handlerClass) { String className = handlerClass.getName().substring(0, handlerClass.getName().lastIndexOf(".")); String useName = className.replaceAll("Handler$", ""); try {//from ww w. j a va 2s .c om @SuppressWarnings("resource") ClassLoader loader = new URLClassLoader(new URL[] { handlerClass.getParentFile().toURI().toURL() }, GenericHandler.class.getClassLoader()); Class<?> clazz = loader.loadClass(className); Object object = clazz.newInstance(); if (!(object instanceof GenericHandler)) { this.plugin.getUtilsManager().log("Not a handler: " + useName, Level.WARNING); } else { GenericHandler handler = (GenericHandler) object; handler.init(this.plugin); this.handlers.put(useName, handler); this.plugin.getUtilsManager().log("Loaded handler: " + useName); } } catch (Exception exception) { this.plugin.getUtilsManager().log("Error loading handler: " + useName, Level.SEVERE); } }
From source file:org.jsonschema2pojo.integration.json.JsonTypesIT.java
@Test @SuppressWarnings("rawtypes") public void arrayTypePropertiesProduceLists() throws Exception { ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/json/array.json", "com.example", config("sourceType", "json")); Class<?> arrayType = resultsClassLoader.loadClass("com.example.Array"); Class<?> itemType = resultsClassLoader.loadClass("com.example.A"); Object deserialisedValue = OBJECT_MAPPER.readValue(this.getClass().getResourceAsStream("/json/array.json"), arrayType);// w w w. j ava 2 s . c om List<?> valueA = (List) arrayType.getMethod("getA").invoke(deserialisedValue); assertThat(((ParameterizedType) arrayType.getMethod("getA").getGenericReturnType()) .getActualTypeArguments()[0], is(equalTo((Type) itemType))); assertThat((Integer) itemType.getMethod("get0").invoke(valueA.get(0)), is(0)); assertThat((Integer) itemType.getMethod("get1").invoke(valueA.get(1)), is(1)); assertThat((Integer) itemType.getMethod("get2").invoke(valueA.get(2)), is(2)); Object valueB = arrayType.getMethod("getB").invoke(deserialisedValue); assertThat(valueB, is(instanceOf(List.class))); assertThat(((ParameterizedType) arrayType.getMethod("getB").getGenericReturnType()) .getActualTypeArguments()[0], is(equalTo((Type) Integer.class))); }