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:ClassUtils.java
/** * Helper for invoking a constructor with one parameter. * //from w ww . j a v a2 s.c om * @param className Class of which an instance is to be allocated * @param param Parameter * @param paramClass Type of the parameter * @throws ClassNotFoundException * @throws SecurityException * @throws NoSuchMethodException * @throws IllegalArgumentException * @throws InstantiationException * @throws IllegalAccessException * @throws InvocationTargetException */ public static Object createObject(String className, Object param, Class paramClass) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { Class clazzImpl = ClassUtils.forName(className); Constructor ctor = clazzImpl.getConstructor(new Class[] { paramClass }); Object instance = ctor.newInstance(new Object[] { param }); return instance; }
From source file:com.feedzai.commons.sql.abstraction.engine.DatabaseFactory.java
/** * Gets a database connection from the specified properties. * * @param p The database properties./*from w w w . j a va 2 s. c o m*/ * @return A reference of the specified database engine. * @throws DatabaseFactoryException If the class specified does not exist or its not well implemented. */ public static DatabaseEngine getConnection(Properties p) throws DatabaseFactoryException { PdbProperties pdbProperties = new PdbProperties(p, true); AbstractDatabaseEngine de = null; final String engine = pdbProperties.getEngine(); if (StringUtils.isBlank(engine)) { throw new DatabaseFactoryException("pdb.engine property is mandatory"); } try { Class<?> c = Class.forName(engine); Constructor cons = c.getConstructor(PdbProperties.class); de = (AbstractDatabaseEngine) cons.newInstance(pdbProperties); Class<? extends AbstractTranslator> tc = de.getTranslatorClass(); if (pdbProperties.isTranslatorSet()) { final Class<?> propertiesTranslator = Class.forName(pdbProperties.getTranslator()); if (!AbstractTranslator.class.isAssignableFrom(propertiesTranslator)) { throw new DatabaseFactoryException("Provided translator does extend from AbstractTranslator."); } tc = (Class<? extends AbstractTranslator>) propertiesTranslator; } final Injector injector = Guice.createInjector( new PdbModule.Builder().withTranslator(tc).withPdbProperties(pdbProperties).build()); injector.injectMembers(de); return de; } catch (DatabaseFactoryException e) { throw e; } catch (Exception e) { throw new DatabaseFactoryException(e); } }
From source file:org.objectweb.proactive.extensions.timitspmd.util.charts.Utilities.java
/** * Exports a JFreeChart to a SVG file.// www.j av a2 s. c o m * * @param chart * JFreeChart to export * @param bounds * the dimensions of the viewport * @param svgFile * the output file. * @throws IOException * if writing the svgFile fails. */ public static void saveChartAsSVG(JFreeChart chart, Rectangle bounds, File svgFile) throws IOException { try { Class<?> GDI = Class.forName("org.apache.batik.dom.GenericDOMImplementation"); // Get a DOMImplementation and create an XML document Method getDOMImplementation = GDI.getMethod("getDOMImplementation", new Class<?>[0]); DOMImplementation domImpl = (DOMImplementation) getDOMImplementation.invoke(null, new Object[0]); org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null); // Create an instance of the SVG Generator Class<?> SG2D = Class.forName("org.apache.batik.svggen.SVGGraphics2D"); Method streamMethod = SG2D.getMethod("stream", new Class<?>[] { Writer.class, boolean.class }); Constructor<?> SG2DConstr = SG2D.getConstructor(new Class<?>[] { org.w3c.dom.Document.class }); Object svgGenerator = SG2DConstr.newInstance(document); // draw the chart in the SVG generator chart.draw((Graphics2D) svgGenerator, bounds); // Write svg file OutputStream outputStream = new FileOutputStream(svgFile); Writer out = new OutputStreamWriter(outputStream, "UTF-8"); streamMethod.invoke(svgGenerator, new Object[] { out, true /* use css */ }); outputStream.flush(); outputStream.close(); out.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:Main.java
/** * Converts the given object to an object of the specified type. The object is * casted directly if possible, or else a new object is created using the * destination type's public constructor that takes the original object as * input (except when converting to {@link String}, which uses the * {@link Object#toString()} method instead). In the case of primitive types, * returns an object of the corresponding wrapped type. If the destination * type does not have an appropriate constructor, returns null. * // w ww .j a va 2 s. c o m * @param <T> Type to which the object should be converted. * @param value The object to convert. * @param type Type to which the object should be converted. */ public static <T> T convert(final Object value, final Class<T> type) { if (value == null) return getNullValue(type); // ensure type is well-behaved, rather than a primitive type final Class<T> saneType = getNonprimitiveType(type); // cast the existing object, if possible if (canCast(value, saneType)) return cast(value, saneType); // special cases for strings if (value instanceof String) { // source type is String final String s = (String) value; if (s.isEmpty()) { // return null for empty strings return getNullValue(type); } // use first character when converting to Character if (saneType == Character.class) { final Character c = new Character(s.charAt(0)); @SuppressWarnings("unchecked") final T result = (T) c; return result; } } if (saneType == String.class) { // destination type is String; use Object.toString() method final String sValue = value.toString(); @SuppressWarnings("unchecked") final T result = (T) sValue; return result; } // wrap the original object with one of the new type, using a constructor try { final Constructor<T> ctor = saneType.getConstructor(value.getClass()); return ctor.newInstance(value); } catch (final Exception exc) { // no known way to convert return null; } }
From source file:Main.java
public static void setGL16Mode() { System.err.println("Orion::setGL16Mode"); try {/* ww w .ja va 2 s . co m*/ if (successful) { Constructor RegionParamsConstructor = epdControllerRegionParamsClass.getConstructor(new Class[] { Integer.TYPE, Integer.TYPE, Integer.TYPE, Integer.TYPE, epdControllerWaveClass }); Object localRegionParams = RegionParamsConstructor .newInstance(new Object[] { 0, 0, 600, 800, waveEnums[1] }); // Wave = GU Method epdControllerSetRegionMethod = epdControllerClass.getMethod("setRegion", new Class[] { String.class, epdControllerRegionClass, epdControllerRegionParamsClass, epdControllerModeClass }); epdControllerSetRegionMethod.invoke(null, new Object[] { "Orion", regionEnums[2], localRegionParams, modeEnums[2] }); // Mode = ONESHOT_ALL } } catch (Exception e) { e.printStackTrace(); } }
From source file:Main.java
public static Drawable showUninstallAPKIcon(Context context, String apkPath) { String PATH_PackageParser = "android.content.pm.PackageParser"; String PATH_AssetManager = "android.content.res.AssetManager"; try {//from www .j ava 2 s. c om Class<?> pkgParserCls = Class.forName(PATH_PackageParser); Class<?>[] typeArgs = new Class[1]; typeArgs[0] = String.class; Constructor<?> pkgParserCt = pkgParserCls.getConstructor(typeArgs); Object[] valueArgs = new Object[1]; valueArgs[0] = apkPath; Object pkgParser = pkgParserCt.newInstance(valueArgs); DisplayMetrics metrics = new DisplayMetrics(); metrics.setToDefaults(); typeArgs = new Class[4]; typeArgs[0] = File.class; typeArgs[1] = String.class; typeArgs[2] = DisplayMetrics.class; typeArgs[3] = Integer.TYPE; Method pkgParser_parsePackageMtd = pkgParserCls.getDeclaredMethod("parsePackage", typeArgs); valueArgs = new Object[4]; valueArgs[0] = new File(apkPath); valueArgs[1] = apkPath; valueArgs[2] = metrics; valueArgs[3] = 0; Object pkgParserPkg = pkgParser_parsePackageMtd.invoke(pkgParser, valueArgs); Field appInfoFld = pkgParserPkg.getClass().getDeclaredField("applicationInfo"); ApplicationInfo info = (ApplicationInfo) appInfoFld.get(pkgParserPkg); Class<?> assetMagCls = Class.forName(PATH_AssetManager); Constructor<?> assetMagCt = assetMagCls.getConstructor((Class[]) null); Object assetMag = assetMagCt.newInstance((Object[]) null); typeArgs = new Class[1]; typeArgs[0] = String.class; Method assetMag_addAssetPathMtd = assetMagCls.getDeclaredMethod("addAssetPath", typeArgs); valueArgs = new Object[1]; valueArgs[0] = apkPath; assetMag_addAssetPathMtd.invoke(assetMag, valueArgs); Resources res = context.getResources(); typeArgs = new Class[3]; typeArgs[0] = assetMag.getClass(); typeArgs[1] = res.getDisplayMetrics().getClass(); typeArgs[2] = res.getConfiguration().getClass(); Constructor<?> resCt = Resources.class.getConstructor(typeArgs); valueArgs = new Object[3]; valueArgs[0] = assetMag; valueArgs[1] = res.getDisplayMetrics(); valueArgs[2] = res.getConfiguration(); res = (Resources) resCt.newInstance(valueArgs); if (info.icon != 0) { Drawable icon = res.getDrawable(info.icon); return icon; } } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:com.linkedin.pinot.core.query.scheduler.QuerySchedulerFactory.java
private static @Nullable QueryScheduler getQuerySchedulerByClassName(String className, Configuration schedulerConfig, QueryExecutor queryExecutor) { try {//from ww w . jav a 2 s.c om Constructor<?> constructor = Class.forName(className).getDeclaredConstructor(Configuration.class, QueryExecutor.class); constructor.setAccessible(true); return (QueryScheduler) constructor.newInstance(new Object[] { schedulerConfig, queryExecutor }); } catch (Exception e) { LOGGER.error("Failed to instantiate scheduler class by name: {}", className, e); return null; } }
From source file:net.buffalo.protocal.util.ClassUtil.java
public static Object convertValue(Object value, Class targetType) { if (value.getClass().equals(targetType)) return value; if (targetType.isPrimitive()) { targetType = getWrapperClass(targetType); }/*from w w w . jav a 2s . c om*/ if (targetType.isAssignableFrom(value.getClass())) return value; if ((value instanceof String || value instanceof Number) && Number.class.isAssignableFrom(targetType)) { try { Constructor ctor = targetType.getConstructor(new Class[] { String.class }); return ctor.newInstance(new Object[] { value.toString() }); } catch (Exception e) { LOGGER.error("convert type error", e); throw new RuntimeException( "Cannot convert from " + value.getClass().getName() + " to " + targetType, e); } } if (targetType.isArray() && Collection.class.isAssignableFrom(value.getClass())) { Collection collection = (Collection) value; Object array = Array.newInstance(targetType.getComponentType(), collection.size()); int i = 0; for (Iterator iter = collection.iterator(); iter.hasNext();) { Object val = iter.next(); Array.set(array, i++, val); } return array; } if (Collection.class.isAssignableFrom(targetType) && value.getClass().isArray()) { return Arrays.asList((Object[]) value); } throw new IllegalArgumentException( "Cannot convert from " + value.getClass().getName() + " to " + targetType); }
From source file:Main.java
public static void enterA2Mode() { System.err.println("Orion::enterA2Mode"); try {/* w w w . j av a2 s .c o m*/ Constructor RegionParamsConstructor = epdControllerRegionParamsClass.getConstructor(new Class[] { Integer.TYPE, Integer.TYPE, Integer.TYPE, Integer.TYPE, epdControllerWaveClass, Integer.TYPE }); Object localRegionParams = RegionParamsConstructor .newInstance(new Object[] { 0, 0, 600, 800, waveEnums[2], 16 }); // Wave = DU Method epdControllerSetRegionMethod = epdControllerClass.getMethod("setRegion", new Class[] { String.class, epdControllerRegionClass, epdControllerRegionParamsClass }); epdControllerSetRegionMethod.invoke(null, new Object[] { "Orion", regionEnums[2], localRegionParams }); Thread.sleep(100L); localRegionParams = RegionParamsConstructor .newInstance(new Object[] { 0, 0, 600, 800, waveEnums[3], 14 }); // Wave = A2 epdControllerSetRegionMethod.invoke(null, new Object[] { "Orion", regionEnums[2], localRegionParams }); } catch (Exception e) { e.printStackTrace(); } }
From source file:it.doqui.index.ecmengine.client.engine.EcmEngineDelegateFactory.java
private static EcmEngineDelegate getClassInstance(String ecmEngineDelegateImplName, Log logger) throws EcmEngineDelegateInstantiationException { EcmEngineDelegate classInstance = null; logger.debug("[EcmEngineDelegateFactory::getClassInstance] BEGIN"); try {/*w ww. ja v a 2s. c om*/ logger.debug("[EcmEngineDelegateFactory::getClassInstance] " + "Caricamento classe: " + ecmEngineDelegateImplName); final Class delegateClass = Class.forName(ecmEngineDelegateImplName); final Constructor constructor = delegateClass.getConstructor(new Class[] { Log.class }); classInstance = (EcmEngineDelegate) constructor.newInstance(new Object[] { logger }); } catch (ClassNotFoundException e) { logger.error("[EcmEngineDelegateFactory::getClassInstance] " + "FATAL: classe non trovata."); throw new EcmEngineDelegateInstantiationException("Classe non trovata.", e); } catch (NoSuchMethodException e) { logger.error( "[EcmEngineDelegateFactory::getClassInstance] " + "FATAL: nessun costruttore compatibile."); throw new EcmEngineDelegateInstantiationException("Nessun costruttore compatibile.", e); } catch (InstantiationException e) { logger.error("[EcmEngineDelegateFactory::getClassInstance] " + "FATAL: errore di istanziazione."); throw new EcmEngineDelegateInstantiationException("Errore di istanziazione.", e); } catch (IllegalAccessException e) { logger.error("[EcmEngineDelegateFactory::getClassInstance] " + "FATAL: errore di accesso."); throw new EcmEngineDelegateInstantiationException("Errore di accesso.", e); } catch (InvocationTargetException e) { logger.error("[EcmEngineDelegateFactory::getClassInstance] " + "FATAL: eccezione nel target invocato."); throw new EcmEngineDelegateInstantiationException("Eccezione nel target invocato.", e); } finally { logger.debug("[EcmEngineDelegateFactory::getClassInstance] END"); } return classInstance; }