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()); } }
/** * 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()); } }
@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); } }
public static void main(String[] args) throws Exception { Class clazz = Class.forName("com.mtl.spring.aop.helloworld.ArithmeticCalculatorLoggingProxy"); Object object = clazz.newInstance(); Method[] methods = clazz.getMethods(); StringBuffer sb = new StringBuffer(); sb.append("public class ") .append(object.getClass().getCanonicalName()) .append("{\n") .append("Object object ") .append("\n"); Constructor[] constructors = clazz.getConstructors(); for (Constructor constructor : constructors) { sb.append("\npublic ").append(constructor.getName()).append("("); Class<?> p[] = constructor.getParameterTypes(); for (int j = 0; j < p.length; ++j) { sb.append(p[j].getName() + " arg" + j); if (j < p.length - 1) { sb.delete(sb.length() - 1, sb.length()); } } sb.append(") {").append("\n\n"); sb.append("user.role.cotain(\"/admin/add\") {"); sb.append("\n System.currentTimeMillis();\n"); sb.append("this.object = ").append("arg0"); sb.append("}"); sb.append(" \nSystem.currentTimeMillis();\n"); sb.append("\n}"); } sb.append("\n\n}"); System.out.println(sb); for (Method method : methods) { System.out.println(method.getName()); } }
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; } } } }
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; }
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."); } } }
public static void main(String[] args) { if (args.length < 1) { print(usage); System.exit(0); } int lines = 0; try { Class<?> c = Class.forName(args[0]); Method[] methods = c.getMethods(); Constructor[] ctors = c.getConstructors(); if (args.length == 1) { for (Method method : methods) print(p.matcher(method.toString()).replaceAll("")); for (Constructor ctor : ctors) print(p.matcher(ctor.toString()).replaceAll("")); lines = methods.length + ctors.length; } else { for (Method method : methods) if (method.toString().indexOf(args[1]) != -1) { print(p.matcher(method.toString()).replaceAll("")); lines++; } for (Constructor ctor : ctors) if (ctor.toString().indexOf(args[1]) != -1) { print(p.matcher(ctor.toString()).replaceAll("")); lines++; } } } catch (ClassNotFoundException e) { print("No such class: " + e); } }
@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; }
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 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; } }
static { final String[] parts = Bukkit.class.getName().split("."); if (parts.length == 4) { InventoryUtil.version = ""; } else { InventoryUtil.version = "." + parts[4]; } Field tiinv = null; Field ttitle = null; Field thandle = null; Field tcontainerCounter = null; Constructor<?> topenWindowPacket = null; Field tplayerConnection = null; Method tsendPacket; try { tiinv = getVersionedClass("org.bukkit.craftbukkit.inventory.CraftInventory") .getDeclaredField("inventory"); tiinv.setAccessible(true); ttitle = getVersionedClass( "org.bukkit.craftbukkit.inventory.CraftInventoryCustom$MinecraftInventory") .getDeclaredField("title"); ttitle.setAccessible(true); thandle = getVersionedClass("org.bukkit.craftbukkit.entity.CraftEntity").getDeclaredField("handle"); thandle.setAccessible(true); tcontainerCounter = getVersionedClass("net.minecraft.server.EntityPlayer") .getDeclaredField("containerCounter"); tcontainerCounter.setAccessible(true); thandle = getVersionedClass("org.bukkit.craftbukkit.entity.CraftEntity").getDeclaredField("handle"); thandle.setAccessible(true); topenWindowPacket = getVersionedClass("net.minecraft.server.PacketPlayOutOpenWindow") .getDeclaredConstructor( Integer.TYPE, Integer.TYPE, String.class, Integer.TYPE, Boolean.TYPE); topenWindowPacket.setAccessible(true); tplayerConnection = getVersionedClass("net.minecraft.server.EntityPlayer") .getDeclaredField("playerConnection"); tplayerConnection.setAccessible(true); tsendPacket = getVersionedClass("net.minecraft.server.PlayerConnection") .getDeclaredMethod( "sendPacket", topenWindowPacket.getDeclaringClass().getSuperclass()); tsendPacket.setAccessible(true); } catch (Exception ex) { throw new ExceptionInInitializerError(ex); } iinvField = tiinv; titleField = ttitle; handleField = thandle; containerCounterField = tcontainerCounter; openWindowPacketConstructor = topenWindowPacket; playerConnectionField = tplayerConnection; sendPacket = tsendPacket; }
@Test public void checkThatConstructorIsProtected() { for (Constructor<?> constr : Earth.class.getDeclaredConstructors()) { assertTrue( "Constructors should be protected to allow subclasses of singleton", Modifier.isProtected(constr.getModifiers())); } }
public Constructor getConstructor(Class... parameterTypes) throws NoSuchMethodException { if (constructors != null) { for (Constructor c : constructors) { if (c.isPublic() && c.match(parameterTypes)) return c; } } throw new NoSuchMethodException(); }
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 Imports ofConstructors(@Nonnull final Iterable<Constructor> constructors) { Check.notNull(constructors, "attributes"); final List<Import> imports = Lists.newArrayList(); for (final Constructor constructor : constructors) { imports.addAll(ofAnnotations(constructor.getAnnotations()).asList()); imports.addAll(ofAttributes(constructor.getAttributes()).asList()); } return new Imports(imports); }
/** * @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); }
/* Check that you aren't exposing java.lang.Class.<init>. */ private static void setAccessible0(AccessibleObject obj, boolean flag) throws SecurityException { if (obj instanceof Constructor && flag == true) { Constructor<?> c = (Constructor<?>) obj; if (c.getDeclaringClass() == Class.class) { throw new SecurityException("Can not make a java.lang.Class" + " constructor accessible"); } } obj.override = flag; }
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]"); }
@Override public void dispose() { for (int i = 0; i < entities.size; i++) entities.get(i).dispose(); entities.clear(); for (Constructor<T> constructor : constructors.values()) constructor.dispose(); constructors.clear(); models.clear(); }
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; }
@NotNull public static <T> Constructor<T> getDefaultConstructor(final Class<T> aClass) { try { final Constructor<T> constructor = aClass.getConstructor(); constructor.setAccessible(true); return constructor; } catch (NoSuchMethodException e) { LOG.error("No default constructor in " + aClass, e); 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); } }
/** @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; }
@Override public final Set<String> getOnlyConstructorsImports() { final Imports imports = new Imports(); for (final Constructor constructor : constructors) { imports.addAll(constructor.getParamsTypes()); } return imports.asSet(); }
/** * 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; } }
/** * 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)); }