List of usage examples for java.lang Class getConstructor
@CallerSensitive public Constructor<T> getConstructor(Class<?>... parameterTypes) throws NoSuchMethodException, SecurityException
From source file:it.cnr.icar.eric.common.spi.LifeCycleManagerFactory.java
/** * Creates the instance of the pluginClass *//* w ww. j a v a 2s . com*/ private Object createPluginInstance(String pluginClass) throws Exception { Object plugin = null; if (log.isDebugEnabled()) { log.debug("pluginClass = " + pluginClass); } Class<?> theClass = Class.forName(pluginClass); //try to invoke constructor using Reflection, //if this fails then try invoking getInstance() try { Constructor<?> constructor = theClass.getConstructor((java.lang.Class[]) null); plugin = constructor.newInstance(new Object[0]); } catch (Exception e) { //log.warn("No accessible constructor. " + // "invoking getInstance() instead."); Method factory = theClass.getDeclaredMethod("getInstance", (java.lang.Class[]) null); plugin = factory.invoke((java.lang.Class[]) null, new Object[0]); } return plugin; }
From source file:it.cnr.icar.eric.common.spi.QueryManagerFactory.java
/** * Creates the instance of the pluginClass *//*from ww w . ja v a2 s . c om*/ private Object createPluginInstance(String pluginClass) throws Exception { Object plugin = null; if (log.isDebugEnabled()) { log.debug("pluginClass = " + pluginClass); } Class<?> theClass = Class.forName(pluginClass); //try to invoke constructor using Reflection, //if this fails then try invoking getInstance() try { Constructor<?> constructor = theClass.getConstructor((java.lang.Class[]) null); plugin = constructor.newInstance(new Object[0]); } catch (Exception e) { //log.warn("No accessible constructor. " + // "invoking getInstance() instead."); Method factory = theClass.getDeclaredMethod("getInstance", (java.lang.Class[]) null); plugin = factory.invoke(null, new Object[0]); } return plugin; }
From source file:it.cnr.icar.eric.server.event.EventManagerFactory.java
/** * Creates the instance of the pluginClass */// ww w . ja v a 2 s. c om private Object createPluginInstance(String pluginClass) throws Exception { Object plugin = null; if (log.isDebugEnabled()) { log.debug("pluginClass = " + pluginClass); } Class<?> theClass = Class.forName(pluginClass); //try to invoke constructor using Reflection, //if this fails then try invoking getInstance() try { Constructor<?> constructor = theClass.getConstructor((java.lang.Class[]) null); plugin = constructor.newInstance(new Object[0]); } catch (Exception e) { //log.warn(ServerResourceBundle.getInstance().getString("message.NoAccessibleConstructorInvokingGetInstanceInstead")); Method factory = theClass.getDeclaredMethod("getInstance", (java.lang.Class[]) null); plugin = factory.invoke(null, new Object[0]); } return plugin; }
From source file:org.openwms.core.aop.FireAfterTransactionAspect.java
/** * Only {@link ApplicationEvent}s are created and published over Springs * {@link ApplicationContext}./* ww w. j av a 2s . co m*/ * * @param publisher * The instance that is publishing the event * @param events * Stores a list of event classes to fire * @throws Exception * Any exception is re-thrown */ @Async public void fireEventAsync(Object publisher, FireAfterTransactionAsynchronous events) throws Exception { for (int i = 0; i < events.events().length; i++) { Class<? extends EventObject> event = events.events()[i]; if (RootApplicationEvent.class.isAssignableFrom(event)) { LOGGER.debug("Sending event:" + event); ctx.publishEvent((RootApplicationEvent) event.getConstructor(Object.class).newInstance(publisher)); } } }
From source file:com.openmeap.web.form.ParameterMapBuilder.java
public void fromParameters(Object obj, Map<String, Object> parameters, String prefix) throws ParameterMapBuilderException { Class clazz = obj.getClass(); for (Map.Entry<String, Object> entry : parameters.entrySet()) { String formName = entry.getKey().replaceFirst(prefix, ""); if (entry.getValue() == null || (String.class.isAssignableFrom(entry.getValue().getClass()) && StringUtils.isBlank((String) entry.getValue()))) { continue; }/*w w w . ja v a2 s.c o m*/ Method getterMethod = methodForFormName(clazz, formName); if (getterMethod == null) { continue; } Method setterMethod = PropertyUtils.setterForGetterMethod(getterMethod); Constructor constructor = null; Class<?> valueClass = null; try { valueClass = getterMethod.getReturnType(); constructor = valueClass.getConstructor(valueClass); } catch (Exception e) { ;//throw new ParameterMapBuilderException(e); } Object value = null; try { if (this.useParameterMapUtilsFirstValue) { value = ParameterMapUtils.firstValue(formName, (Map) parameters); } else { value = parameters.get(formName); } if (value != null) { if (constructor != null) { value = constructor.newInstance(value); } else { value = PropertyUtils.correctCasting(valueClass, value); } } } catch (Exception e) { throw new ParameterMapBuilderException(e); } try { setterMethod.invoke(obj, value); } catch (Exception e) { throw new ParameterMapBuilderException(e); } } }
From source file:net.dmulloy2.ultimatearena.api.SimpleArenaType.java
@Override public ArenaConfig newConfig(ArenaZone az) { Class<? extends ArenaConfig> clazz = getArenaConfig(); Validate.notNull(clazz, "ArenaConfig class cannot be null!"); try {//from w w w .ja v a 2 s . c o m Constructor<? extends ArenaConfig> constructor = clazz.getConstructor(ArenaZone.class); return constructor.newInstance(az); } catch (InvocationTargetException ex) { throw new RuntimeException("Failed to create new " + clazz.getName() + " instance.", ex); } catch (Throwable ex) { throw Throwables.propagate(ex); } }
From source file:com.adito.agent.client.ProxyUtil.java
/** * Attempt to proxy settings from Internet Explorer. * /*w w w .j ava 2 s . com*/ * @return internet explorer proxy settings * @throws IOException if IE settings could not be obtained for some reason */ public static BrowserProxySettings lookupIEProxySettings() throws IOException { try { Vector addresses = new Vector(); Vector proxies = new Vector(); String proxyServerValue = null; String proxyOveride = null; /* Only use jRegistry if on Windows, running 1.3 or up Java * and NOT Windows Vista with JDK6.0 (because of jvm crash) */ if (Utils.isSupportedJRE("+1.3") && Utils.isSupportedPlatform( "Windows") /*&& !(Utils.isSupportedOSVersion("+6.0") && Utils.isSupportedJRE("+1.6"))*/) { /* * We can use jRegistryKey API to lookup IE settings in the * registry */ // RegistryKey key = new RegistryKey(RootKey.HKEY_CURRENT_USER, // "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"); //$NON-NLS-1$ String proxyEnable = WinRegistry.getRegistryValue("user", "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", "ProxyEnable", "0"); if (proxyEnable != null) { //$NON-NLS-1$ /* * We have ProxyEnable so check to see if we are using a * proxy */ if (proxyEnable.equals("1")) { //$NON-NLS-1$ //$NON-NLS-2$ proxyServerValue = WinRegistry.getRegistryValue("user", "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", "ProxyServer", null); if (proxyServerValue != null) { //$NON-NLS-1$ /** * We have some proxy settings. The values will be * in the format "server.proxy.net:8888" or */ proxyOveride = WinRegistry.getRegistryValue("user", "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", "ProxyOverride", null); } } else { } } } else { if (System.getProperty("java.vendor").startsWith("Microsoft")) { //$NON-NLS-1$ //$NON-NLS-2$ try { Class clazz = Class.forName("com.ms.lang.RegKey"); //$NON-NLS-1$ int userRoot = clazz.getField("USER_ROOT").getInt(null); //$NON-NLS-1$ int keyOpenAll = clazz.getField("KEYOPEN_ALL").getInt(null); //$NON-NLS-1$ // #ifdef DEBUG log.info(Messages.getString("ProxyUtil.lookingForRoot")); //$NON-NLS-1$ // #endif Object rootKey = clazz.getMethod("getRootKey", new Class[] { int.class }).invoke(null, //$NON-NLS-1$ new Object[] { new Integer(userRoot) }); // #ifdef DEBUG log.info(Messages.getString("ProxyUtil.getIERegistryKey")); //$NON-NLS-1$ // #endif Object key = clazz.getConstructor(new Class[] { clazz, String.class, int.class }) .newInstance(new Object[] { rootKey, "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", //$NON-NLS-1$ new Integer(keyOpenAll) }); // #ifdef DEBUG log.info(Messages.getString("ProxyUtil.checkingIfProxyEnabled")); //$NON-NLS-1$ // #endif if (((Integer) (clazz.getMethod("getIntValue", new Class[] { String.class }).invoke(key, //$NON-NLS-1$ new Object[] { "ProxyEnable" }))).intValue() == 1) { //$NON-NLS-1$ // #ifdef DEBUG log.info(Messages.getString("ProxyUtil.gettingProxyServerList")); //$NON-NLS-1$ // #endif proxyServerValue = (String) (clazz.getMethod("getStringValue", //$NON-NLS-1$ new Class[] { String.class, String.class }) .invoke(key, new Object[] { "ProxyServer", "" })); //$NON-NLS-1$ //$NON-NLS-2$ // #ifdef DEBUG log.info(Messages.getString("ProxyUtil.gettingProxyOverides")); //$NON-NLS-1$ // #endif proxyOveride = (String) (clazz .getMethod("getStringValue", new Class[] { String.class, String.class }) //$NON-NLS-1$ .invoke(key, new Object[] { "ProxyOverride", "" })); //$NON-NLS-1$ //$NON-NLS-2$ } } catch (Throwable t) { t.printStackTrace(); } } else { // #ifdef DEBUG log.info(MessageFormat.format(Messages.getString("ProxyUtil.unsupportedJavaRuntime"), //$NON-NLS-1$ new Object[] { System.getProperty("java.version"), //$NON-NLS-1$ System.getProperty("java.vendor") })); //$NON-NLS-1$ // #endif } } ProxyInfo p; if (proxyServerValue != null && proxyServerValue.indexOf(';') > -1) { /** * Format is multiple * "ftp=ftp.com:4444;gopher=gopher.com:3333;http=198.162.1.119:8888;https=https.com:2222;socks=socks.com:1111" */ StringTokenizer tokens = new StringTokenizer(proxyServerValue, ";"); //$NON-NLS-1$ while (tokens.hasMoreTokens()) { p = createProxyInfo(tokens.nextToken(), "IE Proxy Settings"); //$NON-NLS-1$ proxies.addElement(p); } } else if (proxyServerValue != null) { /** * Format is single "http=server.proxy.net:8888" or * "server.proxy.net:8888" */ p = createProxyInfo(proxyServerValue, "IE Proxy Settings"); //$NON-NLS-1$ proxies.addElement(p); } BrowserProxySettings bps = new BrowserProxySettings(); bps.setBrowser("Internet Explorer"); //$NON-NLS-1$ bps.setProxies(new ProxyInfo[proxies.size()]); proxies.copyInto(bps.getProxies()); if (proxyOveride != null) { StringTokenizer tokens = new StringTokenizer(proxyOveride, ";"); //$NON-NLS-1$ while (tokens.hasMoreTokens()) { addresses.addElement(tokens.nextToken()); } } bps.setBypassAddr(new String[addresses.size()]); addresses.copyInto(bps.getBypassAddr()); return bps; } catch (Throwable t) { t.printStackTrace(); throw new IOException(MessageFormat.format(Messages.getString("ProxyUtil.failedToLookupIEProxies"), //$NON-NLS-1$ new Object[] { t.getMessage() })); } }
From source file:com.ewcms.web.pubsub.PubsubServlet.java
private PubsubSenderable createPubsubSender(String path) { String name = null;/*ww w . ja v a 2s . c om*/ if (StringUtils.indexOf(path, '/') == -1) { name = pathSender.get(path); } else { String root = StringUtils.substringBeforeLast(path, "/"); name = pathSender.get(root); if (name == null) { String middle = StringUtils.substringAfter(root, "/"); name = pathSender.get(middle); } } if (StringUtils.isNotBlank(name)) { try { Class<?> clazz = Class.forName(name); Class<?>[] argsClass = new Class<?>[] { String.class, ServletContext.class }; Constructor<?> cons = clazz.getConstructor(argsClass); return (PubsubSenderable) cons.newInstance(new Object[] { path, this.getServletContext() }); } catch (Exception e) { logger.error("PubsubSender create error:{}", e.toString()); } } return new NoneSender(); }
From source file:com.scaleunlimited.cascading.DatumCompilerTest.java
@Test public void testUUID() throws Exception { CompiledDatum result = DatumCompiler.generate(MyUUIDDatumTemplate.class); File baseDir = new File("build/test/DatumCompilerTest/testUUID/"); FileUtils.deleteDirectory(baseDir);//from w w w.j a v a 2 s .co m File srcDir = new File(baseDir, result.getPackageName().replaceAll("\\.", "/")); assertTrue(srcDir.mkdirs()); File codeFile = new File(srcDir, result.getClassName() + ".java"); OutputStream os = new FileOutputStream(codeFile); IOUtils.write(result.getClassCode(), os, "UTF-8"); os.close(); // Compile with Janino, give it a try. We have Janino since // it's a cascading dependency, but probably want to add a test // dependency on it. ClassLoader cl = new JavaSourceClassLoader(this.getClass().getClassLoader(), // parentClassLoader new File[] { baseDir }, // optionalSourcePath (String) null // optionalCharacterEncoding ); // WARNING - we have to use xxxDatumTemplate as the base name, so that the code returned // by the compiler is for type xxxDatum. Otherwise when we try to load the class here, // we'll likely get the base (template) class, which will mask our generated class. Class clazz = cl.loadClass(result.getPackageName() + "." + result.getClassName()); assertEquals("MyUUIDDatum", clazz.getSimpleName()); Constructor c = clazz.getConstructor(UUID.class); BaseDatum datum = (BaseDatum) c.newInstance(UUID.randomUUID()); // Verify that it can be serialized with Hadoop. // TODO figure out why Hadoop serializations aren't available??? /* BasePlatform testPlatform = new HadoopPlatform(DatumCompilerTest.class); Tap tap = testPlatform.makeTap( testPlatform.makeBinaryScheme(datum.getFields()), testPlatform.makePath("build/test/DatumCompilerTest/testSimpleSchema/")); TupleEntryCollector writer = tap.openForWrite(testPlatform.makeFlowProcess()); writer.add(datum.getTuple()); writer.close(); TupleEntryIterator iter = tap.openForRead(testPlatform.makeFlowProcess()); TupleEntry te = iter.next(); // TODO how to test round-trip? */ }
From source file:org.crazydog.util.spring.ClassUtils.java
/** * Determine whether the given class has a public constructor with the given signature, * and return it if available (else return {@code null}). * <p>Essentially translates {@code NoSuchMethodException} to {@code null}. * @param clazz the clazz to analyze/*from w w w .jav a2 s. co m*/ * @param paramTypes the parameter types of the method * @return the constructor, or {@code null} if not found * @see Class#getConstructor */ public static <T> Constructor<T> getConstructorIfAvailable(Class<T> clazz, Class<?>... paramTypes) { org.springframework.util.Assert.notNull(clazz, "Class must not be null"); try { return clazz.getConstructor(paramTypes); } catch (NoSuchMethodException ex) { return null; } }