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 static <T> Constructor<T> findConstructor(Class<T> cls, boolean canFixAccess) throws IllegalArgumentException { try { Constructor<T> ctor = cls.getDeclaredConstructor(); if (canFixAccess) { checkAndFixAccess(ctor); } else { // Has to be public... if (!Modifier.isPublic(ctor.getModifiers())) { throw new IllegalArgumentException( "Default constructor for " + cls.getName() + " is not accessible (non-public?): not allowed to try modify access via Reflection: can not instantiate type"); } } return ctor; } catch (NoSuchMethodException e) {; } catch (Exception e) { ClassUtil.unwrapAndThrowAsIAE( e, "Failed to find default constructor of class " + cls.getName() + ", problem: " + e.getMessage()); } return null; }
@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); } }
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); } }
protected void _addConstructorMixIns(Class<?> mixin) { MemberKey[] ctorKeys = null; int ctorCount = (_constructors == null) ? 0 : _constructors.size(); for (Constructor<?> ctor : mixin.getDeclaredConstructors()) { switch (ctor.getParameterTypes().length) { case 0: if (_defaultConstructor != null) { _addMixOvers(ctor, _defaultConstructor, false); } break; default: if (ctorKeys == null) { ctorKeys = new MemberKey[ctorCount]; for (int i = 0; i < ctorCount; ++i) { ctorKeys[i] = new MemberKey(_constructors.get(i).getAnnotated()); } } MemberKey key = new MemberKey(ctor); for (int i = 0; i < ctorCount; ++i) { if (!key.equals(ctorKeys[i])) { continue; } _addMixOvers(ctor, _constructors.get(i), true); break; } } } }
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); } }
private void validateClass(Class<?> source, ValidationProblemCollector problems) { int modifiers = source.getModifiers(); if (Modifier.isInterface(modifiers)) { problems.add("Must be a class, not an interface"); } if (source.getEnclosingClass() != null) { if (Modifier.isStatic(modifiers)) { if (Modifier.isPrivate(modifiers)) { problems.add("Class cannot be private"); } } else { problems.add("Enclosed classes must be static and non private"); } } Constructor<?>[] constructors = source.getDeclaredConstructors(); for (Constructor<?> constructor : constructors) { if (constructor.getParameterTypes().length > 0) { problems.add("Cannot declare a constructor that takes arguments"); break; } } Field[] fields = source.getDeclaredFields(); for (Field field : fields) { int fieldModifiers = field.getModifiers(); if (!field.isSynthetic() && !(Modifier.isStatic(fieldModifiers) && Modifier.isFinal(fieldModifiers))) { problems.add(field, "Fields must be static final."); } } }
@SuppressWarnings("unchecked") public static <T> Constructor<T> findConstructor(Class<T> type, Class<?>... paramTypes) { Constructor<T>[] ctors = (Constructor<T>[]) type.getConstructors(); for (Constructor<T> ctor : ctors) if (typesMatch(paramTypes, ctor.getParameterTypes())) return ctor; return null; }
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 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; }
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]"); }
/** * @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); }
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; }
/** @see jaskell.compiler.JaskellVisitor#visit(Constructor) */ public Object visit(Constructor a) { Type ret = a.getType(); if (ret != null) return ret; String vname = a.getName(); ConstructorDefinition def = (ConstructorDefinition) a.lookup(vname); if (def == null) // unknown symbol throw new CompilerException("Unknown constructor " + vname); ret = new TypeInstantiator(def.getType()).instance(); a.setType(ret); return ret; }
/** 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; } } }
@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); } }
/** {@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); } }
public void printAll(Class c) { Constructor[] cs = this.getAllConstructorsFromClass(c); System.out.println(" Constructors:"); for (Constructor constructor : cs) { System.out.print(" " + constructor); if (constructor.getDeclaringClass() != c) System.out.println(" (inherited from " + constructor.getDeclaringClass().getName() + ")"); else System.out.println(); } System.out.println(" Methods:"); Method[] ms = this.getAllMethodsFromClass(c); for (Method method : ms) { System.out.print(" " + method); if (method.getDeclaringClass() != c) System.out.println(" (inherited from " + method.getDeclaringClass().getName() + ")"); else System.out.println(); } System.out.println(" Classes:"); Class[] cls = this.getClassesFromClass(c); for (Class class1 : cls) { System.out.println(" " + class1); } System.out.println(" Fields:"); Field[] fs = this.getFieldsFromClass(c); for (Field field : fs) { System.out.print(" " + field); if (field.getDeclaringClass() != c) System.out.println(" (inherited from " + field.getDeclaringClass().getName() + ")"); else System.out.println(); } System.out.println(" Interfaces:"); Class[] is = this.getInterfacesFromClass(c); for (Class class2 : is) { System.out.println(" " + class2); } System.out.println(" Local Methods:"); Method[] mls = this.getLocalMethodsFromClass(c); for (Method method2 : mls) { System.out.print(" " + method2); if (method2.getDeclaringClass() != c) System.out.println(" (inherited from " + method2.getDeclaringClass().getName() + ")"); else System.out.println(); } }
/** * 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); }
/** * Finds the constructor of the given class that is compatible with the given arguments. * * @param type the class to find the constructor of * @param args the arguments * @return the constructor */ public static Constructor findConstructor(Class<?> type, Object[] args) { outer: for (Constructor constructor : type.getConstructors()) { Class<?>[] paramTypes = constructor.getParameterTypes(); if (paramTypes.length != args.length) continue; for (int i = 0; i < args.length; i++) { Object arg = args[i]; if (arg != null && !paramTypes[i].isAssignableFrom(arg.getClass())) continue outer; if (arg == null && paramTypes[i].isPrimitive()) continue outer; } return constructor; } throw new GrammarException( "No constructor found for %s and the given %s arguments", type, args.length); }
/** * 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; } }
/** @param addParamAnnotations Whether parameter annotations are to be added as well */ protected void _addMixOvers( Constructor<?> mixin, AnnotatedConstructor target, boolean addParamAnnotations) { for (Annotation a : mixin.getDeclaredAnnotations()) { if (_annotationIntrospector.isHandled(a)) { target.addOrOverride(a); } } if (addParamAnnotations) { Annotation[][] pa = mixin.getParameterAnnotations(); for (int i = 0, len = pa.length; i < len; ++i) { for (Annotation a : pa[i]) { target.addOrOverrideParam(i, a); } } } }
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}); }
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); } }
private boolean isCompatible(Constructor<?> constructor, Object... arguments) { try { constructor.newInstance(arguments); return true; } catch (Exception e) { return false; } }
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(); }
/** {@inheritDoc} */ @Override public HadoopJob createJob(Class<? extends HadoopJob> jobCls, HadoopJobId jobId, IgniteLogger log) throws IgniteCheckedException { assert jobCls != null; try { Constructor<? extends HadoopJob> constructor = jobCls.getConstructor(HadoopJobId.class, HadoopDefaultJobInfo.class, IgniteLogger.class); return constructor.newInstance(jobId, this, log); } // NB: java.lang.NoClassDefFoundError may be thrown from Class#getConstructor() call. catch (Throwable t) { if (t instanceof Error) throw (Error) t; throw new IgniteCheckedException(t); } }
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++; } } }
/** * Prints all constructors of a class * * @param cl a class */ public static void printConstructors(Class cl) { Constructor[] constructors = cl.getDeclaredConstructors(); for (Constructor c : constructors) { String name = c.getName(); System.out.print(" "); String modifiers = Modifier.toString(c.getModifiers()); if (modifiers.length() > 0) System.out.print(modifiers + " "); System.out.print(name + "("); // print parameter types Class[] paramTypes = c.getParameterTypes(); for (int j = 0; j < paramTypes.length; j++) { if (j > 0) System.out.print(", "); System.out.print(paramTypes[j].getName()); } System.out.println(");"); } }