public CircuitElementView instantiateElement( UUID elementUUID, float positionX, float positionY, CircuitElementManager elementManager, WireManager wireManager) throws InvocationTargetException, IllegalAccessException, InstantiationException, NoSuchMethodException { Class<? extends CircuitElementView> viewType = ElementTypeUUID.VIEW_MAP.get(elementUUID); if (viewType == null) throw new IllegalArgumentException("Missing element view UUID"); Class<? extends CircuitElement> elementType = ElementTypeUUID.ELEMENT_MAP.get(elementUUID); if (elementType == null) throw new IllegalArgumentException("Missing element type UUID"); Constructor<? extends CircuitElementView> viewConstructor; viewConstructor = viewType.getConstructor( Context.class, CircuitElement.class, float.class, float.class, WireManager.class); Constructor<? extends CircuitElement> elementConstructor; elementConstructor = elementType.getConstructor(CircuitElementManager.class); CircuitElement element = elementConstructor.newInstance(elementManager); return viewConstructor.newInstance(context, element, 0, 0, wireManager); }
/** * Factory method, equivalent to a "fromXML" for step creation. Looks for a class with the same * name as the XML tag, with the first letter capitalized. For example, <call /> is * abbot.script.Call. */ public static Step createStep(Resolver resolver, Element el) throws InvalidScriptException { String tag = el.getName(); Map attributes = createAttributeMap(el); String name = tag.substring(0, 1).toUpperCase() + tag.substring(1); if (tag.equals(TAG_WAIT)) { attributes.put(TAG_WAIT, "true"); name = "Assert"; } try { name = "abbot.script." + name; Log.debug("Instantiating " + name); Class cls = Class.forName(name); try { // Steps with contents require access to the XML element Class[] argTypes = new Class[] {Resolver.class, Element.class, Map.class}; Constructor ctor = cls.getConstructor(argTypes); return (Step) ctor.newInstance(new Object[] {resolver, el, attributes}); } catch (NoSuchMethodException nsm) { // All steps must support this ctor Class[] argTypes = new Class[] {Resolver.class, Map.class}; Constructor ctor = cls.getConstructor(argTypes); return (Step) ctor.newInstance(new Object[] {resolver, attributes}); } } catch (ClassNotFoundException cnf) { String msg = Strings.get("step.unknown_tag", new Object[] {tag}); throw new InvalidScriptException(msg); } catch (InvocationTargetException ite) { Log.warn(ite); throw new InvalidScriptException(ite.getTargetException().getMessage()); } catch (Exception exc) { Log.warn(exc); throw new InvalidScriptException(exc.getMessage()); } }
public Bean(String classPackage, String clazz, ClassLoaderStrategy cls, Bean topLevelBean) throws Exception { // Get the no-arg constructor and create the bean try { Class classOfBean = ObjectXml.getClassOfBean((ClassLoader) cls, classPackage + "." + clazz); Constructor ct = null; // check whether this class is an inner class if (classOfBean.getEnclosingClass() != null) { ct = classOfBean.getConstructor(new Class[] {classOfBean.getEnclosingClass()}); beanObject = ct.newInstance(new Object[] {topLevelBean.getBeanObject()}); } else { ct = classOfBean.getConstructor((Class[]) null); beanObject = ct.newInstance((Object[]) null); } // Get an array of property descriptors beanInfo = Introspector.getBeanInfo(classOfBean); PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); // load property descriptors into hashtable propDesc = new Properties(); for (int i = 0; i < pds.length; i++) { propDesc.put(pds[i].getName(), pds[i]); } } catch (Exception e) { System.err.println("Exception creating bean: " + e.getMessage()); e.printStackTrace(); throw e; } }
private BrowserLauncher createBrowserLauncher( Class c, String browserStartCommand, String sessionId, SeleneseQueue queue) { try { BrowserLauncher browserLauncher; if (null == browserStartCommand) { Constructor ctor = c.getConstructor(new Class[] {int.class, String.class}); Object[] args = new Object[] {new Integer(server.getPort()), sessionId}; browserLauncher = (BrowserLauncher) ctor.newInstance(args); } else { Constructor ctor = c.getConstructor(new Class[] {int.class, String.class, String.class}); Object[] args = new Object[] { new Integer(SeleniumServer.getPortDriversShouldContact()), sessionId, browserStartCommand }; browserLauncher = (BrowserLauncher) ctor.newInstance(args); } if (browserLauncher instanceof SeleneseQueueAware) { ((SeleneseQueueAware) browserLauncher).setSeleneseQueue(queue); } return browserLauncher; } catch (InvocationTargetException e) { throw new RuntimeException( "failed to contruct launcher for " + browserStartCommand + "for" + e.getTargetException()); } catch (Exception e) { throw new RuntimeException(e); } }
public void apply() throws IllegalAccessException, InvocationTargetException, InstantiationException { if (type.isEnum()) { for (T instance : type.getEnumConstants()) { assertThat( instance.toString(), is( type.getCanonicalName().substring(type.getPackage().getName().length() + 1) + "." + ((Enum<?>) instance).name())); } return; } for (Constructor<?> constructor : type.getDeclaredConstructors()) { if (constructor.isSynthetic() && skipSynthetic) { continue; } constructor.setAccessible(true); Class<?>[] parameterTypes = constructor.getParameterTypes(); Object[] actualArguments = new Object[parameterTypes.length]; Object[] otherArguments = new Object[parameterTypes.length]; int index = 0; for (Class<?> parameterType : parameterTypes) { putInstance(parameterType, actualArguments, otherArguments, index++); } int testIndex = 0; @SuppressWarnings("unchecked") T instance = (T) constructor.newInstance(actualArguments); assertThat(instance, is(instance)); assertThat(instance, not(is((Object) null))); assertThat(instance, not(is(new Object()))); Object similarInstance = constructor.newInstance(actualArguments); assertThat(instance.hashCode(), is(similarInstance.hashCode())); assertThat(instance, is(similarInstance)); if (skipToString) { assertThat(instance.toString(), notNullValue()); } else if (optionalToStringRegex == null) { checkString(instance); } else { assertThat(instance.toString(), new RegexMatcher(optionalToStringRegex)); } for (Object otherArgument : otherArguments) { Object[] compareArguments = new Object[actualArguments.length]; int argumentIndex = 0; for (Object actualArgument : actualArguments) { if (argumentIndex == testIndex) { compareArguments[argumentIndex] = otherArgument; } else { compareArguments[argumentIndex] = actualArgument; } argumentIndex++; } Object unlikeInstance = constructor.newInstance(compareArguments); assertThat(instance.hashCode(), not(is(unlikeInstance))); assertThat(instance, not(is(unlikeInstance))); testIndex++; } } }
/** * Create a channel with the given capacity and semaphore implementations instantiated from the * supplied class * * @exception IllegalArgumentException if capacity less or equal to zero. * @exception NoSuchMethodException If class does not have constructor that intializes permits * @exception SecurityException if constructor information not accessible * @exception InstantiationException if semaphore class is abstract * @exception IllegalAccessException if constructor cannot be called * @exception InvocationTargetException if semaphore constructor throws an exception */ public SemaphoreControlledChannel(int capacity, Class semaphoreClass) throws IllegalArgumentException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException { if (capacity <= 0) throw new IllegalArgumentException(); capacity_ = capacity; Class[] longarg = {Long.TYPE}; Constructor ctor = semaphoreClass.getDeclaredConstructor(longarg); Object[] cap = {Long.valueOf(capacity)}; putGuard_ = (Semaphore) (ctor.newInstance(/*(Object[]) GemStoneAddition*/ cap)); Object[] zero = {Long.valueOf(0)}; takeGuard_ = (Semaphore) (ctor.newInstance(/*(Object[]) GemStoneAddition*/ zero)); }
private Filter newInstance(API api) throws Exception { for (Constructor c : api.filter().getDeclaredConstructors()) { c.setAccessible(true); Class[] ps = c.getParameterTypes(); if (ps.length == 1 && RequestArguments.class.isAssignableFrom(ps[0])) return (Filter) c.newInstance(this); } for (Constructor c : api.filter().getDeclaredConstructors()) { Class[] ps = c.getParameterTypes(); if (ps.length == 0) return (Filter) c.newInstance(); } throw new Exception("Class " + api.filter().getName() + " must have an empty constructor"); }
/** * _more_ * * @param entry _more_ * @param className _more_ * @param properties _more_ * @return _more_ * @throws Exception _more_ */ private RecordFile doMakeRecordFile(Entry entry, String className, Hashtable properties) throws Exception { Class c = Misc.findClass(className); Constructor ctor = Misc.findConstructor(c, new Class[] {String.class, Hashtable.class}); if (ctor != null) { return (RecordFile) ctor.newInstance(new Object[] {entry.getFile().toString(), properties}); } ctor = Misc.findConstructor(c, new Class[] {String.class}); if (ctor != null) { return (RecordFile) ctor.newInstance(new Object[] {entry.getResource().getPath()}); } throw new IllegalArgumentException("Could not find constructor for " + className); }
ProxyConnection createProxyConnection() throws Exception { // we should always have a separate handler for each proxy connection, so // that object methods behave as expected... the handler covers // all object methods on behalf of the proxy. InvocationHandler handler = new ProxyConnectionInvocationHandler(); return (ProxyConnection) CON_PROXY_CTOR.newInstance(new Object[] {handler}); }
/** * Returns an instance of a proxy class for the specified interfaces that dispatches method * invocations to the specified invocation handler. This method is equivalent to: * * <pre> * Proxy.getProxyClass(loader, interfaces). * getConstructor(new Class[] { InvocationHandler.class }). * newInstance(new Object[] { handler }); * </pre> * * <p>{@code Proxy.newProxyInstance} throws {@code IllegalArgumentException} for the same reasons * that {@code Proxy.getProxyClass} does. * * @param loader the class loader to define the proxy class * @param interfaces the list of interfaces for the proxy class to implement * @param h the invocation handler to dispatch method invocations to * @return a proxy instance with the specified invocation handler of a proxy class that is defined * by the specified class loader and that implements the specified interfaces * @throws IllegalArgumentException if any of the restrictions on the parameters that may be * passed to {@code getProxyClass} are violated * @throws NullPointerException if the {@code interfaces} array argument or any of its elements * are {@code null}, or if the invocation handler, {@code h}, is {@code null} */ public static Object newProxyInstance( ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException { if (h == null) { throw new NullPointerException(); } /* * Look up or generate the designated proxy class. */ Class<?> cl = getProxyClass(loader, interfaces); /* * Invoke its constructor with the designated invocation handler. */ try { Constructor cons = cl.getConstructor(constructorParams); return cons.newInstance(new Object[] {h}); } catch (NoSuchMethodException e) { throw new InternalError(e.toString()); } catch (IllegalAccessException e) { throw new InternalError(e.toString()); } catch (InstantiationException e) { throw new InternalError(e.toString()); } catch (InvocationTargetException e) { throw new InternalError(e.toString()); } }
/** * Create a default object of the given type. Prefers constructors with as few arguments as * possible. Creates an empty proxy for interfaces. * * @param type type to instantiate * @return default instance * @throws Exception if the default instance could not be created */ private static Object instantiateType(Class<?> type) throws Exception { if (type.isPrimitive()) return Defaults.defaultValue(type); else if (type == Void.class) return null; else if (type.isArray()) return Array.newInstance(type, 0); else if (type.isInterface()) return Proxy.newProxyInstance( type.getClassLoader(), new Class[] {type}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return null; } }); // Take a constructor with as few params as possible Constructor constructor = type.getDeclaredConstructors()[0]; for (Constructor<?> c : type.getDeclaredConstructors()) { if (c.getParameterTypes().length < constructor.getParameterTypes().length) constructor = c; } Object[] params = new Object[constructor.getParameterTypes().length]; for (int i = 0; i < constructor.getParameterTypes().length; i++) { params[i] = instantiateType(constructor.getParameterTypes()[i]); } return constructor.newInstance(params); }
@SuppressWarnings("unchecked") private <T> T _get(Class<T> type, Set<Class<?>> seenTypes) { if (!seenTypes.add(type)) { throw new IllegalStateException("Cycle in dependencies for " + type); } Object singleton = singletons.get(type); if (singleton != null) { return (T) singleton; } try { Constructor<T> constructor = getConstructor(type); Class<?>[] parameterTypes = constructor.getParameterTypes(); Object[] parameters = new Object[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { parameters[i] = _get(parameterTypes[i], seenTypes); } T instance = postProcess(constructor.newInstance(parameters)); singletons.put(type, instance); return instance; } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { throw new IllegalStateException("Unable to create instance of " + type); } }
private static void testPotato( Class<? extends Collection> implClazz, Class<? extends List> argClazz) throws Throwable { try { System.out.printf("implClazz=%s, argClazz=%s\n", implClazz.getName(), argClazz.getName()); final int iterations = 100000; final List<Integer> list = (List<Integer>) argClazz.newInstance(); final Integer one = Integer.valueOf(1); final List<Integer> oneElementList = Collections.singletonList(one); final Constructor<? extends Collection> constr = implClazz.getConstructor(Collection.class); final Thread t = new CheckedThread() { public void realRun() { for (int i = 0; i < iterations; i++) { list.add(one); list.remove(one); } } }; t.setDaemon(true); t.start(); for (int i = 0; i < iterations; i++) { Collection<?> coll = constr.newInstance(list); Object[] elts = coll.toArray(); check(elts.length == 0 || (elts.length == 1 && elts[0] == one)); } } catch (Throwable t) { unexpected(t); } }
public <BLOCK extends Block> BLOCK newBlock( String name, Class<BLOCK> cls, Class itemClass, String title) { try { int id = config.getBlock(name, 4095).getInt(); Constructor<BLOCK> ctor = cls.getConstructor(int.class); BLOCK block = ctor.newInstance(id); String qualName = assetKey + ":" + name; block.setUnlocalizedName(qualName); // block.func_111022_d(qualName.toLowerCase()); // Set default icon name // block.func_111022_d(qualName); // Set default icon name block.setTextureName(qualName); // Set default icon name GameRegistry.registerBlock(block, itemClass); if (title != null) { LanguageRegistry.addName(block, title); if (clientSide) { // System.out.printf("%s: BaseMod.newBlock: %s: creative tab = %s\n", // this, block.getUnlocalizedName(), block.getCreativeTabToDisplayOn()); if (block.getCreativeTabToDisplayOn() == null && !title.startsWith("[")) block.setCreativeTab(CreativeTabs.tabMisc); } } if (block instanceof IBlock) registeredBlocks.add((IBlock) block); return block; } catch (Exception e) { throw new RuntimeException(e); } }
private boolean isCompatible(Constructor<?> constructor, Object... arguments) { try { constructor.newInstance(arguments); return true; } catch (Exception e) { return false; } }
private Validator newValidator(API api) throws Exception { for (Constructor c : api.validator().getDeclaredConstructors()) { c.setAccessible(true); Class[] ps = c.getParameterTypes(); return (Validator) c.newInstance(); } return null; }
/** * @param cacheName Cache name. * @param key Key. * @return Data key. * @throws Exception In case of error. */ private Object key(String cacheName, int key) throws Exception { Class<?> cls = Class.forName(GridSpringDynamicCacheManager.class.getName() + "$DataKey"); Constructor<?> cons = cls.getDeclaredConstructor(String.class, Object.class); cons.setAccessible(true); return cons.newInstance(cacheName, key); }
private static Object createArgumentPlaceholderForUnknownClass( Class<?> clazz, Integer placeholderId) throws IllegalAccessException, InstantiationException { FinalClassArgumentCreator<?> creator = FINAL_CLASS_ARGUMENT_CREATORS.get(clazz); if (creator != null) return creator.createArgumentPlaceHolder(placeholderId); for (Constructor constructor : clazz.getConstructors()) { Class<?>[] params = constructor.getParameterTypes(); if (params.length != 1) continue; try { if (params[0] == String.class) return constructor.newInstance(String.valueOf(placeholderId)); if (isNumericClass(params[0])) return constructor.newInstance(placeholderId); } catch (IllegalAccessException e1) { } catch (InvocationTargetException e2) { } } return clazz.newInstance(); }
private static void testImplementation(Class<? extends Collection> implClazz) throws Throwable { testPotato(implClazz, Vector.class); testPotato(implClazz, CopyOnWriteArrayList.class); final Constructor<? extends Collection> constr = implClazz.getConstructor(Collection.class); final Collection<Object> coll = constr.newInstance(Arrays.asList(new String[] {})); coll.add(1); equal(coll.toString(), "[1]"); }
public static Object loadFrame( JopSession session, String className, String instance, boolean scrollbar) throws ClassNotFoundException { if (className.indexOf(".pwg") != -1) { GrowFrame frame = new GrowFrame( className, session.getGdh(), instance, new GrowFrameCb(session), session.getRoot()); frame.validate(); frame.setVisible(true); } else { Object frame; if (instance == null) instance = ""; JopLog.log( "JopSpider.loadFrame: Loading frame \"" + className + "\" instance \"" + instance + "\""); try { Class clazz = Class.forName(className); try { Class argTypeList[] = new Class[] {session.getClass(), instance.getClass(), boolean.class}; Object argList[] = new Object[] {session, instance, new Boolean(scrollbar)}; System.out.println("JopSpider.loadFrame getConstructor"); Constructor constructor = clazz.getConstructor(argTypeList); try { frame = constructor.newInstance(argList); } catch (Exception e) { System.out.println( "Class instanciation error: " + className + " " + e.getMessage() + " " + constructor); return null; } // frame = clazz.newInstance(); JopLog.log("JopSpider.loadFrame openFrame"); openFrame(frame); return frame; } catch (NoSuchMethodException e) { System.out.println("NoSuchMethodException: Unable to get frame constructor " + className); } catch (Exception e) { System.out.println( "Exception: Unable to get frame class " + className + " " + e.getMessage()); } } catch (ClassNotFoundException e) { System.out.println("Class not found: " + className); throw new ClassNotFoundException(); } return null; } return null; }
public void addAction(String action) { try { Class<?> c = Class.forName(action); Constructor init = c.getConstructor(new Class[] {MinecraftProcess.class}); Action a = (Action) init.newInstance(new Object[] {mcp}); mcp.addAction(a); } catch (Exception e) { e.printStackTrace(System.err); System.exit(1); } }
/** * Create the default projection for the default class * * @return a default projection */ private ProjectionImpl makeDefaultProjection() { // the default constructor try { Constructor c = projClass.getConstructor(VOIDCLASSARG); return (ProjectionImpl) c.newInstance(VOIDOBJECTARG); } catch (Exception ee) { System.err.println( "ProjectionManager makeDefaultProjection failed to construct class " + projClass); System.err.println(" " + ee); return null; } }
/** Try to create a Java object using a one-string-param constructor. */ public static Object newStringConstructor(String type, String param) throws Exception { Constructor c = Utils.getClass(type).getConstructor(String.class); try { return c.newInstance(param); } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t instanceof Exception) { throw (Exception) t; } else { throw e; } } }
/** {@inheritDoc} */ public T convert(F from) { Object[] initArgs = new Object[argumentConverters.size()]; int i = 0; for (ArgumentConverter<F, Object> argumentConverter : argumentConverters) { initArgs[i++] = argumentConverter.convert(from); } try { return constructor.newInstance(initArgs); } catch (Exception e) { throw new IntrospectionException( "Unable to create an object of class " + constructor.getDeclaringClass().getName(), e); } }
@Override public T create() { Class<T> concreteClass = type.getConcreteClass(); try { Constructor<T> declaredConstructor = concreteClass.getDeclaredConstructor(); declaredConstructor.setAccessible(true); return declaredConstructor.newInstance(); } catch (InvocationTargetException e) { throw UncheckedException.throwAsUncheckedException(e.getTargetException()); } catch (Exception e) { throw UncheckedException.throwAsUncheckedException(e); } }
public void applyBasic() throws IllegalAccessException, InvocationTargetException, InstantiationException { for (Constructor<?> constructor : type.getDeclaredConstructors()) { if (constructor.isSynthetic() && skipSynthetic) { continue; } constructor.setAccessible(true); Class<?>[] parameterTypes = constructor.getParameterTypes(); Object[] actualArguments = new Object[parameterTypes.length]; Object[] otherArguments = new Object[parameterTypes.length]; int index = 0; for (Class<?> parameterType : parameterTypes) { putInstance(parameterType, actualArguments, otherArguments, index++); } @SuppressWarnings("unchecked") T instance = (T) constructor.newInstance(actualArguments); checkString(instance); assertThat(instance, is(instance)); assertThat(instance, not(is((Object) null))); assertThat(instance, not(is(new Object()))); assertThat(instance, not(is(constructor.newInstance(otherArguments)))); } }
static MappedByteBuffer newMappedByteBufferR( int size, long addr, FileDescriptor fd, Runnable unmapper) { MappedByteBuffer dbb; if (directByteBufferRConstructor == null) initDBBRConstructor(); try { dbb = (MappedByteBuffer) directByteBufferRConstructor.newInstance( new Object[] {new Integer(size), new Long(addr), fd, unmapper}); } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { throw new InternalError(e); } return dbb; }
@NotNull public static <T> T createInstance(final Constructor<T> constructor, final Object... args) { try { return constructor.newInstance(args); } catch (InstantiationException e) { LOG.error(e); return null; } catch (IllegalAccessException e) { LOG.error(e); return null; } catch (InvocationTargetException e) { LOG.error(e); return null; } }
/** * Method that can be called to try to create an instantiate of specified type. Instantiation is * done using default no-argument constructor. * * @param canFixAccess Whether it is possible to try to change access rights of the default * constructor (in case it is not publicly accessible) or not. * @throws IllegalArgumentException If instantiation fails for any reason; except for cases where * constructor throws an unchecked exception (which will be passed as is) */ public static <T> T createInstance(Class<T> cls, boolean canFixAccess) throws IllegalArgumentException { Constructor<T> ctor = findConstructor(cls, canFixAccess); if (ctor == null) { throw new IllegalArgumentException( "Class " + cls.getName() + " has no default (no arg) constructor"); } try { return ctor.newInstance(); } catch (Exception e) { ClassUtil.unwrapAndThrowAsIAE( e, "Failed to instantiate class " + cls.getName() + ", problem: " + e.getMessage()); return null; } }
public static <T> T newInstance( Constructor<T> constructor, boolean strict, Object... parameters) { if (!strict) parameters = convertArray(parameters, constructor.getParameterTypes()); Class<T> type = constructor.getDeclaringClass(); if (deprecated(type)) escalator.escalate( "Instantiating a deprecated class: " + type.getName(), BeanUtil.class, null); try { return constructor.newInstance(parameters); } catch (InstantiationException e) { throw ExceptionMapper.configurationException(e, type); } catch (IllegalAccessException e) { throw ExceptionMapper.configurationException(e, type); } catch (InvocationTargetException e) { throw ExceptionMapper.configurationException(e, type); } }