List of usage examples for java.lang.reflect Constructor newInstance
@CallerSensitive @ForceInline public T newInstance(Object... initargs) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
From source file:io.coala.factory.ClassUtil.java
/** * @param returnType the type of the stored property value * @param args the arguments for construction * @return the property value's class instantiated * @throws CoalaException if the property's value is no instance of * valueClass// w w w. j a va2s. com */ @SuppressWarnings("unchecked") public static <T> T instantiate(final Class<T> returnType, final Object... args) throws CoalaException { if (returnType == null) throw CoalaExceptionFactory.VALUE_NOT_SET.create("returnType"); final Class<?>[] argTypes = new Class<?>[args.length]; for (int i = 0; i < args.length; i++) argTypes[i] = args[i] == null ? null : args[i].getClass(); for (Constructor<?> constructor : returnType.getConstructors()) { final Class<?>[] paramTypes = constructor.getParameterTypes(); if (paramTypes.length != args.length) // different argument count, // try next constructor { continue; } boolean match = true; for (int i = 0; match && i < paramTypes.length; i++) { if (args[i] == null && !paramTypes[i].isPrimitive()) argTypes[i] = paramTypes[i]; else if (!isAssignableFrom(paramTypes[i], argTypes[i])) match = false; } if (!match) // no matching parameter types, try next constructor { continue; } try { return (T) constructor.newInstance(args); } catch (final InvocationTargetException exception) { // exception caused by the constructor itself, pass cause thru throw exception.getCause() instanceof CoalaException ? (CoalaException) exception.getCause() : CoalaExceptionFactory.INCONSTRUCTIBLE.create(exception, returnType, Arrays.asList(argTypes)); } catch (final Exception exception) { throw CoalaExceptionFactory.INCONSTRUCTIBLE.create(exception, returnType, Arrays.asList(argTypes)); } } throw CoalaExceptionFactory.INCONSTRUCTIBLE.create(returnType, Arrays.asList(argTypes)); }
From source file:com.bstek.dorado.web.servlet.ServletContextResourceLoader.java
public ServletContextResourceLoader(ServletContext servletContext) { this.servletContext = servletContext; String resourceLoaderClass = servletContext.getInitParameter("resourceLoaderClass"); if (StringUtils.isNotEmpty(StringUtils.trim(resourceLoaderClass))) { ConsoleUtils.outputLoadingInfo("[resourceLoaderClass=" + resourceLoaderClass + "]"); try {/* ww w . j a va2 s . co m*/ @SuppressWarnings("unchecked") Class<ResourceLoader> type = ClassUtils.forName(resourceLoaderClass); Constructor<ResourceLoader> constr = type.getConstructor(new Class[] { ClassLoader.class }); resourceLoader = constr.newInstance(new Object[] { getClass().getClassLoader() }); } catch (Exception e) { logger.error(e, e); } } }
From source file:marshalsec.gadgets.CommonsConfiguration.java
@Args(minArgs = 2, args = { "codebase", "class" }, defaultArgs = { MarshallerBase.defaultCodebase, MarshallerBase.defaultCodebaseClass }) @Primary/*w w w . jav a2 s. c om*/ default Object makeConfigurationMap(UtilFactory uf, String[] args) throws Exception { Object jc = makeConfiguration(uf, args); Class<?> cl = Class.forName("org.apache.commons.configuration.ConfigurationMap"); Constructor<?> cons = cl.getDeclaredConstructor(Configuration.class); cons.setAccessible(true); return uf.makeHashCodeTrigger(cons.newInstance(jc)); }
From source file:it.sample.parser.domain.TipologiaRapporto.java
/** * Restituisce una istanza della classe. */// w ww. j a v a2 s. c o m public Rapporto newInstance(Rapporto rapporto) { try { Class<?>[] intArgsClass = new Class[] { Filiale.class, String.class, String.class }; Object[] intArgs = new Object[] { rapporto.getFiliale(), rapporto.getCategoria(), rapporto.getNumeroRapporto() }; Constructor<? extends Rapporto> constructor = clazz.getConstructor(intArgsClass); return Rapporto.class.cast(constructor.newInstance(intArgs)); } catch (Exception e) { throw new UnsupportedOperationException( clazz.getName() + " non espone un costruttore privo di argomenti."); } }
From source file:javazoom.jlgui.player.amp.playlist.PlaylistFactory.java
/** * Returns Playlist instantied from full qualified class name. *///from w w w . j a v a 2s.com public Playlist getPlaylist() { if (_playlistInstance == null) { String classname = _config.getPlaylistClassName(); boolean interfaceFound = false; try { Class aClass = Class.forName(classname); Class superClass = aClass; // Looking for Playlist interface implementation. while (superClass != null) { Class[] interfaces = superClass.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { if ((interfaces[i].getName()).equals("javazoom.jlgui.player.amp.playlist.Playlist")) { interfaceFound = true; break; } } if (interfaceFound == true) break; superClass = superClass.getSuperclass(); } if (interfaceFound == false) { log.error("Error : Playlist implementation not found in " + classname + " hierarchy"); } else { Class[] argsClass = new Class[] {}; Constructor c = aClass.getConstructor(argsClass); _playlistInstance = (Playlist) (c.newInstance(null)); log.info(classname + " loaded"); } } catch (Exception e) { log.error("Error : " + classname + " : " + e.getMessage()); } } return _playlistInstance; }
From source file:com.xpn.xwiki.plugin.charts.plots.AreaPlotFactory.java
public Plot create(DataSource dataSource, ChartParams params) throws GenerateException, DataSourceException { Class rendererClass = params.getClass(ChartParams.RENDERER); if (rendererClass == null || XYItemRenderer.class.isAssignableFrom(rendererClass)) { XYItemRenderer renderer;//from w w w. jav a 2 s . co m if (rendererClass != null) { try { Constructor ctor = rendererClass.getConstructor(new Class[] {}); renderer = (XYItemRenderer) ctor.newInstance(new Object[] {}); } catch (Throwable e) { throw new GenerateException(e); } } else { renderer = new XYAreaRenderer(); } ChartCustomizer.customizeXYItemRenderer(renderer, params); return XYPlotFactory.getInstance().create(dataSource, renderer, params); } else if (CategoryItemRenderer.class.isAssignableFrom(rendererClass)) { CategoryItemRenderer renderer; if (rendererClass != null) { try { Constructor ctor = rendererClass.getConstructor(new Class[] {}); renderer = (CategoryItemRenderer) ctor.newInstance(new Object[] {}); } catch (Throwable e) { throw new GenerateException(e); } } else { renderer = new AreaRenderer(); } ChartCustomizer.customizeCategoryItemRenderer(renderer, params); return CategoryPlotFactory.getInstance().create(dataSource, renderer, params); } else { throw new GenerateException("Incompatible renderer class: " + rendererClass); } }
From source file:com.xpn.xwiki.plugin.charts.plots.BarPlotFactory.java
public Plot create(DataSource dataSource, ChartParams params) throws GenerateException, DataSourceException { Class rendererClass = params.getClass(ChartParams.RENDERER); if (rendererClass == null || CategoryItemRenderer.class.isAssignableFrom(rendererClass)) { CategoryItemRenderer renderer;/* w w w. j ava 2 s .c o m*/ if (rendererClass != null) { try { Constructor ctor = rendererClass.getConstructor(new Class[] {}); renderer = (CategoryItemRenderer) ctor.newInstance(new Object[] {}); } catch (Throwable e) { throw new GenerateException(e); } } else { renderer = new BarRenderer(); } return CategoryPlotFactory.getInstance().create(dataSource, renderer, params); } else if (XYItemRenderer.class.isAssignableFrom(rendererClass)) { XYItemRenderer renderer; if (rendererClass != null) { try { Constructor ctor = rendererClass.getConstructor(new Class[] {}); renderer = (XYItemRenderer) ctor.newInstance(new Object[] {}); } catch (Throwable e) { throw new GenerateException(e); } } else { renderer = new XYBarRenderer(); // will never run } ChartCustomizer.customizeXYItemRenderer(renderer, params); return XYPlotFactory.getInstance().create(dataSource, renderer, params); } else { throw new GenerateException("Incompatible renderer class: " + rendererClass); } }
From source file:it.cnr.icar.eric.client.admin.AdminShellFactory.java
/** * Creates the instance of the pluginClass *//*from ww w .ja v a2 s . c o m*/ private Object createPluginInstance(String pluginClass) throws Exception { Object plugin = null; log.debug("adminShellClass = " + 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(rb.getString(AdminShell.ADMIN_SHELL_RESOURCES_PREFIX + "noAccessibleConstructor")); Method factory = theClass.getDeclaredMethod("getInstance", (java.lang.Class[]) null); plugin = factory.invoke(null, new Object[0]); } return plugin; }
From source file:net.joinedminds.masserr.util.IdentifiableBeanConverter.java
@Override public Object convert(Class type, Object value) { if (type.isAssignableFrom(value.getClass())) { return value; }// w w w .j av a2s . c o m Constructor constructor; try { try { constructor = type.getConstructor(value.getClass()); return constructor.newInstance(value); } catch (NoSuchMethodException e) { try { constructor = type.getConstructor(String.class); return constructor.newInstance(value.toString()); } catch (NoSuchMethodException e1) { throw new ConversionException("Could not find single parameter constructor.", e1); } } } catch (Exception e) { throw new ConversionException("Could not construct " + type.getName(), e); } }
From source file:com.xpn.xwiki.plugin.charts.plots.PiePlotFactory.java
public Plot create(DataSource dataSource, ChartParams params) throws GenerateException, DataSourceException { DefaultPieDataset dataset = new DefaultPieDataset(); String dataSeries = params.getString(ChartParams.SERIES); if (dataSeries.equals("columns")) { for (int row = 0; row < dataSource.getRowCount(); row++) { if (dataSource.hasHeaderColumn()) { String category = dataSource.getHeaderColumnValue(row); dataset.setValue(category, dataSource.getCell(row, 0)); } else { dataset.setValue("Category " + (row + 1), dataSource.getCell(row, 0)); }//from www .j a v a 2s . co m } } else if (dataSeries.equals("rows")) { for (int column = 0; column < dataSource.getColumnCount(); column++) { if (dataSource.hasHeaderRow()) { String category = dataSource.getHeaderRowValue(column); dataset.setValue(category, dataSource.getCell(0, column)); } else { dataset.setValue("Category " + (column + 1), dataSource.getCell(0, column)); } } } else { throw new GenerateException("Invalid series parameter:" + dataSeries); } Class plotClass = params.getClass(ChartParams.RENDERER); PiePlot plot; if (plotClass != null) { try { Constructor ctor = plotClass.getConstructor(new Class[] { PieDataset.class }); plot = (PiePlot) ctor.newInstance(new Object[] { dataset }); } catch (Throwable e) { throw new GenerateException(e); } } else { plot = new PiePlot(dataset); } ChartCustomizer.customizePiePlot(plot, params); return plot; }