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:TimeLib.java
/** * Get a new Date instance of the specified subclass and given long value. * @param type the concrete subclass of the Date instance, must be an * instance of subclass of java.util.Date * @param d the date/time value as a long * @return the new Date instance, or null if the class type is not valid *///w w w .java 2 s .c om public static Date getDate(Class type, long d) { try { Constructor c = type.getConstructor(new Class[] { long.class }); return (Date) c.newInstance(new Object[] { new Long(d) }); } catch (Exception e) { e.printStackTrace(); return null; } }
From source file:info.novatec.testit.livingdoc.util.ClassUtils.java
public static <C> C createInstanceFromClassNameWithArguments(ClassLoader classLoader, String classWithArguments, Class<C> expectedType) throws UndeclaredThrowableException { try {// w w w. j a v a2s .c o m List<String> parameters = toList(escapeValues(classWithArguments.split(";"))); Class<?> klass = ClassUtils.loadClass(classLoader, shift(parameters)); if (!expectedType.isAssignableFrom(klass)) { throw new IllegalArgumentException( "Class " + expectedType.getName() + " is not assignable from " + klass.getName()); } if (parameters.size() == 0) { return expectedType.cast(klass.newInstance()); } String[] args = parameters.toArray(new String[parameters.size()]); Constructor<?> constructor = klass.getConstructor(args.getClass()); return expectedType.cast(constructor.newInstance(new Object[] { args })); } catch (ClassNotFoundException e) { throw new UndeclaredThrowableException(e); } catch (InstantiationException e) { throw new UndeclaredThrowableException(e); } catch (IllegalAccessException e) { throw new UndeclaredThrowableException(e); } catch (NoSuchMethodException e) { throw new UndeclaredThrowableException(e); } catch (InvocationTargetException e) { throw new UndeclaredThrowableException(e); } }
From source file:eu.esdihumboldt.hale.io.geoserver.ResourceBuilder.java
public static <T extends DataStore> ResourceBuilder dataStore(String name, Class<T> dataStoreType) { if (dataStoreType == null) { throw new IllegalArgumentException("DataStore type not specified"); }/*from w w w. jav a 2 s.c om*/ Constructor<T> constructor; try { // TODO: this code assumes a constructor taking a single String // parameter exists constructor = dataStoreType.getConstructor(String.class); return new ResourceBuilder(constructor.newInstance(name)); } catch (Exception e) { throw new RuntimeException("Cannot instantiate DataStore type: " + dataStoreType.getName()); } }
From source file:org.jamwiki.utils.ResourceUtil.java
/** * Given a String representation of a class name (for example, org.jamwiki.db.AnsiDataHandler) * return an instance of the class. The constructor for the class being instantiated must * not take any arguments.// w ww .j a va 2 s.com * * @param className The name of the class being instantiated. * @return A Java Object representing an instance of the specified class. */ public static Object instantiateClass(String className) { if (StringUtils.isBlank(className)) { throw new IllegalArgumentException("Cannot call instantiateClass with an empty class name"); } if (logger.isDebugEnabled()) { logger.debug("Instantiating class: " + className); } try { Class clazz = ClassUtils.forName(className, ClassUtils.getDefaultClassLoader()); Class[] parameterTypes = new Class[0]; Constructor constructor = clazz.getConstructor(parameterTypes); Object[] initArgs = new Object[0]; return constructor.newInstance(initArgs); } catch (ClassNotFoundException e) { throw new IllegalStateException("Invalid class name specified: " + className, e); } catch (NoSuchMethodException e) { throw new IllegalStateException("Specified class does not have a valid constructor: " + className, e); } catch (IllegalAccessException e) { throw new IllegalStateException("Specified class does not have a valid constructor: " + className, e); } catch (InvocationTargetException e) { throw new IllegalStateException("Specified class does not have a valid constructor: " + className, e); } catch (InstantiationException e) { throw new IllegalStateException("Specified class could not be instantiated: " + className, e); } }
From source file:fr.opensagres.xdocreport.core.logging.LogUtils.java
/** * Create a logger/*w w w.j av a 2 s . c om*/ */ protected static Logger createLogger(String loggerName) { if (loggerClass != null) { try { Constructor<? extends AbstractDelegatingLogger> cns = loggerClass.getConstructor(String.class); return cns.newInstance(loggerName); } catch (Exception e) { throw new RuntimeException(e); } } return Logger.getLogger(loggerName, null); }
From source file:edu.cwru.sepia.Main.java
private static Agent[] getAgents(HierarchicalConfiguration config) { String[] participatingAgents = config.getStringArray("agents.ParticipatingAgents"); Agent[] agents = new Agent[participatingAgents.length]; for (int i = 0; i < participatingAgents.length; i++) { String key = "agents." + participatingAgents[i]; HierarchicalConfiguration agentConfig = config.configurationAt(key); String className = agentConfig.getString("ClassName"); int playerId = agentConfig.getInt("PlayerId"); String[] arguments = agentConfig.getStringArray("ConstructorArguments"); try {//from w w w . java2s . co m Class<?> classDef = Class.forName(className); Agent agent = null; try { if (arguments != null && arguments.length != 0) agent = (Agent) classDef.getConstructor(int.class, String[].class).newInstance(playerId, arguments); } catch (Exception e) { } if (agent == null) { @SuppressWarnings("unchecked") Constructor<? extends Agent> constructor = (Constructor<? extends Agent>) classDef .getConstructor(int.class); agent = (Agent) constructor.newInstance(playerId); } agents[i] = agent; } catch (Exception ex) { String errorMessage = String.format("Unable to instantiate %s with playerId %d%s.", className, playerId, (arguments == null ? "" : " and additional arguments " + Arrays.toString(arguments))); logger.log(Level.SEVERE, errorMessage, ex); throw new RuntimeException(ex);//make sure the program fails and the error gets propagated } agents[i].setConfiguration(agentConfig); } return agents; }
From source file:net.big_oh.common.web.filters.ipaddress.IPAddressFilter.java
private static IPAddressFilterRule instantiateIPAddressFilterRule(String className, String constructorParam) { IPAddressFilterRule newIPAddressFilterRule = null; try {/*from w w w . j ava 2 s. co m*/ // Get the class declared in the FilterConfig parameter. Class<?> filterRuleClass = Class.forName(className); // Try to instantiate an instance of the IPAddressFilterRule class // Look for an appropriate constructor that takes a single // java.lang.String Constructor<?> constructor = filterRuleClass.getConstructor(String.class); newIPAddressFilterRule = (IPAddressFilterRule) constructor.newInstance(constructorParam); } catch (ClassNotFoundException cnfe) { logger.error("Could not find a class named " + className); } catch (NoSuchMethodException e) { logger.error("Could not instantiate an instance of class " + className + "."); logger.error(e); } catch (InstantiationException e) { logger.error("Could not instantiate an instance of class " + className + "."); logger.error(e); } catch (IllegalAccessException e) { logger.error("Could not instantiate an instance of class " + className + "."); logger.error(e); } catch (InvocationTargetException e) { logger.error("Could not instantiate an instance of class " + className + "."); logger.error(e); } catch (RuntimeException e) { logger.error("Could not instantiate an instance of class " + className + "."); logger.error(e); } return newIPAddressFilterRule; }
From source file:eu.stratosphere.nephele.profiling.ProfilingUtils.java
/** * Creates an instance of the job manager's profiling component. * /* w ww. j ava 2 s .c om*/ * @param profilerClassName * the class name of the profiling component to load * @param jobManagerBindAddress * the address the job manager's RPC server is bound to * @return an instance of the job manager profiling component or <code>null</code> if an error occurs */ @SuppressWarnings("unchecked") public static JobManagerProfiler loadJobManagerProfiler(String profilerClassName, InetAddress jobManagerBindAddress) { final Class<? extends JobManagerProfiler> profilerClass; try { profilerClass = (Class<? extends JobManagerProfiler>) Class.forName(profilerClassName); } catch (ClassNotFoundException e) { LOG.error("Cannot find class " + profilerClassName + ": " + StringUtils.stringifyException(e)); return null; } JobManagerProfiler profiler = null; try { final Constructor<JobManagerProfiler> constr = (Constructor<JobManagerProfiler>) profilerClass .getConstructor(InetAddress.class); profiler = constr.newInstance(jobManagerBindAddress); } catch (InvocationTargetException e) { LOG.error("Cannot create profiler: " + StringUtils.stringifyException(e)); return null; } catch (NoSuchMethodException e) { LOG.error("Cannot create profiler: " + StringUtils.stringifyException(e)); return null; } catch (InstantiationException e) { LOG.error("Cannot create profiler: " + StringUtils.stringifyException(e)); return null; } catch (IllegalAccessException e) { LOG.error("Cannot create profiler: " + StringUtils.stringifyException(e)); return null; } catch (IllegalArgumentException e) { LOG.error("Cannot create profiler: " + StringUtils.stringifyException(e)); return null; } return profiler; }
From source file:fr.mby.saml2.sp.impl.helper.SecurityHelper.java
/** * Build a private Key from DER resource. * //from w ww . j a v a 2s.c o m * @param certificate * the DER resource * @param pkSpecClass * the java key specification class * @param type * the certificate type * @return the java.security.cert.Certificate * @throws NoSuchMethodException * @throws SecurityException * @throws InvocationTargetException * @throws IllegalAccessException * @throws InstantiationException * @throws IllegalArgumentException * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws IOException */ public static PrivateKey buildPrivateKey(final Resource privateKey, final Class<EncodedKeySpec> pkSpecClass, final String type) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchAlgorithmException, InvalidKeySpecException, IOException { PrivateKey result = null; final Constructor<EncodedKeySpec> keySpecConstructor = pkSpecClass.getConstructor(byte[].class); final byte[] keyBytes = SecurityHelper.readBytesFromFilePath(privateKey); if (keyBytes != null) { final EncodedKeySpec keySpec = keySpecConstructor.newInstance(keyBytes); final KeyFactory pkFactory = KeyFactory.getInstance(type); result = pkFactory.generatePrivate(keySpec); } return result; }
From source file:edu.brown.pools.TypedPoolableObjectFactory.java
/** * @param <X>//from w ww. ja v a 2 s . c o m * @param clazz * @param enable_tracking * @param args * @return */ public static <X extends Poolable> TypedPoolableObjectFactory<X> makeFactory(final Class<X> clazz, final boolean enable_tracking, final Object... args) { Class<?> argsClazz[] = new Class[args.length]; for (int i = 0; i < args.length; i++) { assert (args[i] != null) : "[" + i + "]"; argsClazz[i] = args[i].getClass(); } // FOR final Constructor<X> constructor = ClassUtil.getConstructor(clazz, argsClazz); return new TypedPoolableObjectFactory<X>(enable_tracking) { @Override public X makeObjectImpl() throws Exception { return (constructor.newInstance(args)); } }; }