List of usage examples for java.lang Class newInstance
@CallerSensitive @Deprecated(since = "9") public T newInstance() throws InstantiationException, IllegalAccessException
From source file:com.stratio.deep.commons.utils.Utils.java
/** * Creates a new instance of the given class. * * @param <T> the type parameter * @param clazz the class object for which a new instance should be created. * @return the new instance of class clazz. *//*from w ww .j a v a2 s . c om*/ public static <T extends IDeepType> T newTypeInstance(Class<T> clazz) { try { return clazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new DeepGenericException(e); } }
From source file:de.xirp.ate.ATEManager.java
/** * Executes the a the <code>algorithm( )</code> method from a * given class, which is indicated by is name. * //ww w. j a va 2 s .c o m * @param className * The class to execute the method from. */ public static void execute(String className) { File clazz = new File(Constants.MAZE_CODE_DIR); try { URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { clazz.toURI().toURL() }); Class<?> forName = Class.forName(className, true, classLoader); Method declaredMethod = forName.getDeclaredMethod("algorithm", new Class[0]); //$NON-NLS-1$ declaredMethod.invoke(forName.newInstance(), new Object[0]); } catch (Exception e) { logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$ } }
From source file:com.cloud.consoleproxy.ConsoleProxy.java
public static ConsoleProxyServerFactory getHttpServerFactory() { try {/*from w w w. j a v a 2s .c o m*/ Class<?> clz = Class.forName(factoryClzName); try { ConsoleProxyServerFactory factory = (ConsoleProxyServerFactory) clz.newInstance(); factory.init(ConsoleProxy.ksBits, ConsoleProxy.ksPassword); return factory; } catch (InstantiationException e) { s_logger.error(e.getMessage(), e); return null; } catch (IllegalAccessException e) { s_logger.error(e.getMessage(), e); return null; } } catch (ClassNotFoundException e) { s_logger.warn("Unable to find http server factory class: " + factoryClzName); return new ConsoleProxyBaseServerFactoryImpl(); } }
From source file:ee.ria.xroad.common.conf.globalconf.ConfigurationDirectory.java
private static <T extends ConfProvider> T loadParameters(Path path, Class<T> clazz, T existingInstance) throws Exception { T params = existingInstance != null ? existingInstance : (T) clazz.newInstance(); if (params.hasChanged()) { log.trace("Loading {} from {}", clazz.getSimpleName(), path); params.load(path.toString());// w w w. j a va 2 s .c om } return params; }
From source file:jp.co.acroquest.endosnipe.perfdoctor.rule.RuleInstanceUtil.java
/** * ????????//from w w w . j av a 2s .c o m * ????????????????? * ???????RuleCreateException? * @param className ?? * @return ? * @throws RuleCreateException ???????? */ protected static PerformanceRule createNewInstance(final String className) throws RuleCreateException { PerformanceRule rule; try { Class<?> clazz = Class.forName(className); // PerformanceRule??????ClassCastException????? if (PerformanceRule.class.isAssignableFrom(clazz) == false) { throw new RuleCreateException(PerfConstants.CLASS_TYPE_ERROR, new Object[] { className }); } rule = (PerformanceRule) clazz.newInstance(); } catch (ClassNotFoundException ex) { throw new RuleCreateException(PerfConstants.CLASS_NOT_FOUND, new Object[] { className }); } catch (InstantiationException ex) { throw new RuleCreateException(PerfConstants.NEW_INSTANCE_ERROR, new Object[] { className }); } catch (IllegalAccessException ex) { throw new RuleCreateException(PerfConstants.NEW_INSTANCE_ERROR, new Object[] { className }); } catch (ClassCastException ex) { throw new RuleCreateException(PerfConstants.CLASS_TYPE_ERROR, new Object[] { className }); } return rule; }
From source file:net.radai.beanz.util.ReflectionUtil.java
public static Object instantiate(Type type) { Class<?> erased = erase(type); if (Collection.class.isAssignableFrom(erased)) { return instantiateCollection(erased); }// w w w . j a va 2 s .com try { return erased.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new IllegalStateException(e); } }
From source file:com.all.shared.json.JsonConverter.java
public static <T extends Collection<V>, V> T toCollection(String json, Class<T> collectionType) { T collection = null;/*from w w w .jav a2 s. com*/ JSONArray jsonCollection = JSONArray.fromObject(json); try { collection = collectionType.newInstance(); @SuppressWarnings("unchecked") T tempCollection = (T) JSONArray.toCollection(jsonCollection); collection.addAll(tempCollection); return collection; } catch (Exception ex) { log.error("Could not convert json collection.", ex); } return collection; }
From source file:com.bstek.dorado.core.pkgs.PackageManager.java
private static void doBuildPackageInfos() throws Exception { Map<String, PackageInfo> packageMap = new HashMap<String, PackageInfo>(); Enumeration<URL> defaultContextFileResources = org.springframework.util.ClassUtils.getDefaultClassLoader() .getResources(PACKAGE_PROPERTIES_LOCATION); while (defaultContextFileResources.hasMoreElements()) { URL url = defaultContextFileResources.nextElement(); InputStream in = null;/*from w ww. ja va 2 s . c om*/ try { URLConnection con = url.openConnection(); con.setUseCaches(false); in = con.getInputStream(); Properties properties = new Properties(); properties.load(in); String packageName = properties.getProperty("name"); if (StringUtils.isEmpty(packageName)) { throw new IllegalArgumentException("Package name undefined."); } PackageInfo packageInfo = new PackageInfo(packageName); packageInfo.setAddonVersion(properties.getProperty("addonVersion")); packageInfo.setVersion(properties.getProperty("version")); String dependsText = properties.getProperty("depends"); if (StringUtils.isNotBlank(dependsText)) { List<Dependence> dependences = new ArrayList<Dependence>(); for (String depends : StringUtils.split(dependsText, "; ")) { if (StringUtils.isNotEmpty(depends)) { Dependence dependence = parseDependence(depends); dependences.add(dependence); } } if (!dependences.isEmpty()) { packageInfo.setDepends(dependences.toArray(new Dependence[0])); } } String license = StringUtils.trim(properties.getProperty("license")); if (StringUtils.isNotEmpty(license)) { if (INHERITED.equals(license)) { packageInfo.setLicense(LICENSE_INHERITED); } else { String[] licenses = StringUtils.split(license); licenses = StringUtils.stripAll(licenses); packageInfo.setLicense(licenses); } } packageInfo.setLoadUnlicensed(BooleanUtils.toBoolean(properties.getProperty("loadUnlicensed"))); packageInfo.setClassifier(properties.getProperty("classifier")); packageInfo.setHomePage(properties.getProperty("homePage")); packageInfo.setDescription(properties.getProperty("description")); packageInfo.setPropertiesLocations(properties.getProperty("propertiesConfigLocations")); packageInfo.setContextLocations(properties.getProperty("contextConfigLocations")); packageInfo.setComponentLocations(properties.getProperty("componentConfigLocations")); packageInfo.setServletContextLocations(properties.getProperty("servletContextConfigLocations")); String configurerClass = properties.getProperty("configurer"); if (StringUtils.isNotBlank(configurerClass)) { Class<?> type = ClassUtils.forName(configurerClass); packageInfo.setConfigurer((PackageConfigurer) type.newInstance()); } String listenerClass = properties.getProperty("listener"); if (StringUtils.isNotBlank(listenerClass)) { Class<?> type = ClassUtils.forName(listenerClass); packageInfo.setListener((PackageListener) type.newInstance()); } String servletContextListenerClass = properties.getProperty("servletContextListener"); if (StringUtils.isNotBlank(servletContextListenerClass)) { Class<?> type = ClassUtils.forName(servletContextListenerClass); packageInfo.setServletContextListener((ServletContextListener) type.newInstance()); } if (packageMap.containsKey(packageName)) { PackageInfo conflictPackageInfo = packageMap.get(packageName); StringBuffer conflictInfo = new StringBuffer(20); conflictInfo.append('[').append(conflictPackageInfo.getName()).append(" - ") .append(conflictPackageInfo.getVersion()).append(']'); conflictInfo.append(" and "); conflictInfo.append('[').append(packageInfo.getName()).append(" - ") .append(packageInfo.getVersion()).append(']'); Exception e = new IllegalArgumentException("More than one package \"" + packageName + "\" found. They are " + conflictInfo.toString()); logger.warn(e, e); } packageMap.put(packageName, packageInfo); } catch (Exception e) { throw new IllegalArgumentException("Error occured during parsing \"" + url.getPath() + "\".", e); } finally { if (in != null) { in.close(); } } } List<PackageInfo> calculatedPackages = new ArrayList<PackageInfo>(); for (PackageInfo packageInfo : packageMap.values()) { calculateDepends(packageInfo, calculatedPackages, packageMap); } packageInfosMap.clear(); for (PackageInfo packageInfo : calculatedPackages) { packageInfosMap.put(packageInfo.getName(), packageInfo); } }
From source file:net.sf.excelutils.ExcelParser.java
/** * get a instance by the tag name.//www. jav a2 s . c om * * @param str tag name * @return ITag instance */ public static ITag getTagClass(String str) { String tagName = ""; int keytag = str.indexOf(KEY_TAG); if (keytag < 0) return null; if (!(keytag < str.length() - 1)) return null; String tagRight = str.substring(keytag + 1, str.length()); if (tagRight.startsWith(KEY_TAG) || "".equals(tagRight.trim())) return null; str = str.substring(str.indexOf(KEY_TAG) + KEY_TAG.length(), str.length()); StringTokenizer st = new StringTokenizer(str, " "); if (st.hasMoreTokens()) { tagName = st.nextToken(); } tagName = tagName.substring(0, 1).toUpperCase() + tagName.substring(1, tagName.length()); tagName += "Tag"; // find in tagMap first, if not exist, search in the package ITag tag = (ITag) tagMap.get(tagName); if (tag == null) { Iterator tagPackages = tagPackageMap.values().iterator(); // seach the tag class while (tagPackages.hasNext() && null == tag) { String packageName = (String) tagPackages.next(); try { Class clazz = Class.forName(packageName + "." + tagName); tag = (ITag) clazz.newInstance(); } catch (Exception e) { tag = null; } } if (tag != null) { // find it, cache it tagMap.put(tagName, tag); } } return tag; }
From source file:edu.stanford.epad.common.plugins.impl.ClassFinderTestUtils.java
public static void dynamicClassLoader() { try {//from w w w . j a va 2s. c o m ClassLoader myClassLoader = ClassLoader.getSystemClassLoader(); // Step 2: Define a class to be loaded. String classNameToBeLoaded = "edu.stanford.epad.plugins.first.FirstHandler"; // Step 3: Load the class Class<?> myClass = myClassLoader.loadClass(classNameToBeLoaded); if (myClass != null) { logger.info("dynamicClassLoader found FirstHandler."); // Step 4: create a new instance of that class @SuppressWarnings("unused") Object whatInstance = myClass.newInstance(); } else { logger.info("FirstHandler was not found"); } } catch (Exception e) { logger.warning(e.getMessage(), e); } catch (IncompatibleClassChangeError err) { logger.warning(err.getMessage(), err); } }