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 <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 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); } }
Object createGuiElement(Class cls, EntityPlayer player, World world, int x, int y, int z) { try { try { if (debugGui) System.out.printf( "BaseMod.createGuiElement: Invoking create method of %s for %s in %s\n", cls, player, world); return cls.getMethod( "create", EntityPlayer.class, World.class, int.class, int.class, int.class) .invoke(null, player, world, x, y, z); } catch (NoSuchMethodException e) { if (debugGui) System.out.printf("BaseMod.createGuiElement: Invoking constructor of %s\n", cls); return cls.getConstructor(EntityPlayer.class, World.class, int.class, int.class, int.class) .newInstance(player, world, x, y, z); } } catch (Exception e) { Throwable cause = e.getCause(); System.out.printf("BaseMod.createGuiElement: %s: %s\n", e, cause); if (cause != null) cause.printStackTrace(); else e.printStackTrace(); // throw new RuntimeException(e); return null; } }
// setHandler creates a Proxy object from the passed OSXAdapter and adds it as an // ApplicationListener public static void setHandler(OSXAdapter adapter) { try { Class applicationClass = Class.forName("com.apple.eawt.Application"); if (macOSXApplication == null) { macOSXApplication = applicationClass.getConstructor((Class[]) null).newInstance((Object[]) null); } Class applicationListenerClass = Class.forName("com.apple.eawt.ApplicationListener"); Method addListenerMethod = applicationClass.getDeclaredMethod( "addApplicationListener", new Class[] {applicationListenerClass}); // Create a proxy object around this handler that can be reflectively added as an Apple // ApplicationListener Object osxAdapterProxy = Proxy.newProxyInstance( OSXAdapter.class.getClassLoader(), new Class[] {applicationListenerClass}, adapter); addListenerMethod.invoke(macOSXApplication, new Object[] {osxAdapterProxy}); } catch (ClassNotFoundException cnfe) { System.err.println( "This version of Mac OS X does not support the Apple EAWT. ApplicationEvent handling has been disabled (" + cnfe + ")"); } catch ( Exception ex) { // Likely a NoSuchMethodException or an IllegalAccessException loading/invoking // eawt.Application methods System.err.println("Mac OS X Adapter could not talk to EAWT:"); ex.printStackTrace(); } }
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]"); }
static void jar(String... args) throws Exception { Class c = Class.forName("sun.tools.jar.Main", true, cl); Object instance = c.getConstructor(new Class[] {PrintStream.class, PrintStream.class, String.class}) .newInstance(System.out, System.err, "jar"); boolean result = (Boolean) c.getMethod("run", new Class[] {String[].class}).invoke(instance, new Object[] {args}); if (!result) throw new Exception("jar failed"); }
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); } }
@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; } }
/** * 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; } }
/** {@inheritDoc} */ @Override public void start() throws GridException { if (ctx.isEnterprise()) { Package pkg = getClass().getPackage(); if (pkg == null) throw new GridException( "Internal error (package object was not found) for: " + getClass().getName()); if (ctx.isEnterprise()) { try { Class<?> cls = Class.forName(pkg.getName() + ".GridEnterpriseSecureSessionHandler"); sesHnd = (GridSecureSessionHandler) cls.getConstructor(GridSecureSessionSpi[].class) .newInstance(new Object[] {getProxies()}); } catch (ClassNotFoundException e) { throw new GridException( "Failed to create enterprise secure session handler (implementing class " + "was not found)", e); } catch (InvocationTargetException e) { throw new GridException( "Failed to create enterprise secure session handler (target constructor " + "has thrown an exception", e.getCause()); } catch (InstantiationException e) { throw new GridException( "Failed to create enterprise secure session handler (object cannot be " + "instantiated)", e); } catch (NoSuchMethodException e) { throw new GridException( "Failed to create enterprise secure session handler (target constructor " + "could not be found)", e); } catch (IllegalAccessException e) { throw new GridException( "Failed to create enterprise secure session handler (object access is not" + " allowed)", e); } } } else sesHnd = new GridCommunitySecureSessionHandler(); startSpi(); if (log.isDebugEnabled()) log.debug(startInfo()); }
/** {@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); } }
static Object js_createAdpter(Context cx, Scriptable scope, Object[] args) { int N = args.length; if (N == 0) { throw ScriptRuntime.typeError0("msg.adapter.zero.args"); } Class superClass = null; Class[] intfs = new Class[N - 1]; int interfaceCount = 0; for (int i = 0; i != N - 1; ++i) { Object arg = args[i]; if (!(arg instanceof NativeJavaClass)) { throw ScriptRuntime.typeError2( "msg.not.java.class.arg", String.valueOf(i), ScriptRuntime.toString(arg)); } Class c = ((NativeJavaClass) arg).getClassObject(); if (!c.isInterface()) { if (superClass != null) { throw ScriptRuntime.typeError2("msg.only.one.super", superClass.getName(), c.getName()); } superClass = c; } else { intfs[interfaceCount++] = c; } } if (superClass == null) superClass = ScriptRuntime.ObjectClass; Class[] interfaces = new Class[interfaceCount]; System.arraycopy(intfs, 0, interfaces, 0, interfaceCount); Scriptable obj = ScriptRuntime.toObject(cx, scope, args[N - 1]); Class adapterClass = getAdapterClass(scope, superClass, interfaces, obj); Class[] ctorParms = {ScriptRuntime.ContextFactoryClass, ScriptRuntime.ScriptableClass}; Object[] ctorArgs = {cx.getFactory(), obj}; try { Object adapter = adapterClass.getConstructor(ctorParms).newInstance(ctorArgs); return getAdapterSelf(adapterClass, adapter); } catch (Exception ex) { throw Context.throwAsScriptRuntimeEx(ex); } }
public <ITEM extends Item> ITEM newItem(String name, Class<ITEM> cls, String title) { try { int id = config.getItem(name, 31743).getInt(); Constructor<ITEM> ctor = cls.getConstructor(int.class); ITEM item = ctor.newInstance(id); String qualName = assetKey + ":" + name; item.setUnlocalizedName(qualName); // item.func_111206_d(qualName.toLowerCase()); // Set default icon name // item.func_111206_d(qualName); // Set default icon name item.setTextureName(qualName); // Set default icon name LanguageRegistry.addName(item, title); if (clientSide) { if (item.getCreativeTab() == null) item.setCreativeTab(CreativeTabs.tabMisc); } // System.out.printf("BaseMod.newItem: %s unlocalizedName = %s title = %s\n", // item, item.getUnlocalizedName(), title); return item; } catch (Exception e) { throw new RuntimeException(e); } }
// Needed by NativeJavaObject de-serializer public static Object readAdapterObject(Scriptable self, ObjectInputStream in) throws IOException, ClassNotFoundException { ContextFactory factory; Context cx = Context.getCurrentContext(); if (cx != null) { factory = cx.getFactory(); } else { factory = null; } Class<?> superClass = Class.forName((String) in.readObject()); String[] interfaceNames = (String[]) in.readObject(); Class<?>[] interfaces = new Class[interfaceNames.length]; for (int i = 0; i < interfaceNames.length; i++) interfaces[i] = Class.forName(interfaceNames[i]); Scriptable delegee = (Scriptable) in.readObject(); Class<?> adapterClass = getAdapterClass(self, superClass, interfaces, delegee); Class<?>[] ctorParms = { ScriptRuntime.ContextFactoryClass, ScriptRuntime.ScriptableClass, ScriptRuntime.ScriptableClass }; Object[] ctorArgs = {factory, delegee, self}; try { return adapterClass.getConstructor(ctorParms).newInstance(ctorArgs); } catch (InstantiationException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } catch (NoSuchMethodException e) { } throw new ClassNotFoundException("adapter"); }
/** Look on disk for an editor with the class name 'ocName'. */ PluggableEditor loadEditorFromDisk(String ocName) { // if here, we need to look on disk for a pluggable editor class... log.finer("looking for ocName: " + ocName); try { Class c = myLoader.loadClass(ocName); Constructor constructor = c.getConstructor(new Class[0]); // XXX If the pluggable editor has an error in the constructor, under some // XXX circumstances it can fail so badly that this call never returns, and // XXX the thread hangs! It doesn't even get to the exception handler below... // XXX but sometimes if the constructor fails everything works as expected. Wierd. PluggableEditor editor = (PluggableEditor) constructor.newInstance(new Object[0]); editors.put(ocName, editor); // add the new editor to our list return editor; } catch (Exception e) // expected condition - just means no pluggable editor available { if (e instanceof InvocationTargetException) // rare exception - an error was encountered in the plugin's // constructor. { log.warning("unable to load special editor for: '" + ocName + "' " + e); if (JXConfig.debugLevel >= 1) { log.warning("Error loading plugin class: "); ((InvocationTargetException) e).getTargetException().printStackTrace(); } } log.log(Level.FINEST, "'Expected' Error loading " + ocName, e); editors.put(ocName, NONE); // add a blank place holder - we can't load // an editor for this, and there's no point looking again. (change if want dynamic loading, // i.e. look *every* time) } return null; // only here if an error has occured. }
/** * Creates a new <code>java.awt.Frame</code>. This frame is the root for the AWT components that * will be embedded within the composite. In order for the embedding to succeed, the composite * must have been created with the SWT.EMBEDDED style. * * <p>IMPORTANT: As of JDK1.5, the embedded frame does not receive mouse events. When a * lightweight component is added as a child of the embedded frame, the cursor does not change. In * order to work around both these problems, it is strongly recommended that a heavyweight * component such as <code>java.awt.Panel</code> be added to the frame as the root of all * components. * * @param parent the parent <code>Composite</code> of the new <code>java.awt.Frame</code> * @return a <code>java.awt.Frame</code> to be the parent of the embedded AWT components * @exception IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the parent is null * <li>ERROR_INVALID_ARGUMENT - if the parent Composite does not have the SWT.EMBEDDED style * </ul> * * @since 3.0 */ public static Frame new_Frame(final Composite parent) { if (parent == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); if ((parent.getStyle() & SWT.EMBEDDED) == 0) { SWT.error(SWT.ERROR_INVALID_ARGUMENT); } final int /*long*/ handle = parent.view.id; Class clazz = null; try { String className = embeddedFrameClass != null ? embeddedFrameClass : "apple.awt.CEmbeddedFrame"; if (embeddedFrameClass == null) { clazz = Class.forName(className, true, ClassLoader.getSystemClassLoader()); } else { clazz = Class.forName(className); } } catch (ClassNotFoundException cne) { SWT.error(SWT.ERROR_NOT_IMPLEMENTED, cne); } catch (Throwable e) { SWT.error(SWT.ERROR_UNSPECIFIED, e, " [Error while starting AWT]"); } initializeSwing(); Object value = null; Constructor constructor = null; try { constructor = clazz.getConstructor(new Class[] {long.class}); value = constructor.newInstance(new Object[] {new Long(handle)}); } catch (Throwable e) { SWT.error(SWT.ERROR_NOT_IMPLEMENTED, e); } final Frame frame = (Frame) value; frame.addNotify(); parent.setData(EMBEDDED_FRAME_KEY, frame); /* Forward the iconify and deiconify events */ final Listener shellListener = new Listener() { public void handleEvent(Event e) { switch (e.type) { case SWT.Deiconify: EventQueue.invokeLater( new Runnable() { public void run() { frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_DEICONIFIED)); } }); break; case SWT.Iconify: EventQueue.invokeLater( new Runnable() { public void run() { frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_ICONIFIED)); } }); break; } } }; Shell shell = parent.getShell(); shell.addListener(SWT.Deiconify, shellListener); shell.addListener(SWT.Iconify, shellListener); /* * Generate the appropriate events to activate and deactivate * the embedded frame. This is needed in order to make keyboard * focus work properly for lightweights. */ Listener listener = new Listener() { public void handleEvent(Event e) { switch (e.type) { case SWT.Dispose: Shell shell = parent.getShell(); shell.removeListener(SWT.Deiconify, shellListener); shell.removeListener(SWT.Iconify, shellListener); parent.setVisible(false); EventQueue.invokeLater( new Runnable() { public void run() { try { frame.dispose(); } catch (Throwable e) { } } }); break; case SWT.FocusIn: EventQueue.invokeLater( new Runnable() { public void run() { if (frame.isActive()) return; try { Class clazz = frame.getClass(); Method method = clazz.getMethod( "synthesizeWindowActivation", new Class[] {boolean.class}); if (method != null) method.invoke(frame, new Object[] {new Boolean(true)}); } catch (Throwable e) { e.printStackTrace(); } } }); break; case SWT.Deactivate: EventQueue.invokeLater( new Runnable() { public void run() { if (!frame.isActive()) return; try { Class clazz = frame.getClass(); Method method = clazz.getMethod( "synthesizeWindowActivation", new Class[] {boolean.class}); if (method != null) method.invoke(frame, new Object[] {new Boolean(false)}); } catch (Throwable e) { e.printStackTrace(); } } }); break; } } }; parent.addListener(SWT.FocusIn, listener); parent.addListener(SWT.Deactivate, listener); parent.addListener(SWT.Dispose, listener); parent .getDisplay() .asyncExec( new Runnable() { public void run() { if (parent.isDisposed()) return; final Rectangle clientArea = parent.getClientArea(); EventQueue.invokeLater( new Runnable() { public void run() { frame.setSize(clientArea.width, clientArea.height); frame.validate(); // Bug in Cocoa AWT? For some reason the frame isn't showing up on first // draw. // Toggling visibility seems to be the only thing that works. frame.setVisible(false); frame.setVisible(true); } }); } }); return frame; }
/** @deprecated use or rewrite in terms of ReflectUtils.findProxyConstructor() */ private static Constructor createProxyConstructor(Class intfc) throws NoSuchMethodException { Class[] proxyInterfaces = new Class[] {intfc}; Class proxyCl = Proxy.getProxyClass(C3P0PooledConnection.class.getClassLoader(), proxyInterfaces); return proxyCl.getConstructor(PROXY_CTOR_ARGS); }
private Object deserialize(Node node, boolean setProperty, boolean popBean) throws Exception { Object object = null; currentType = null; currentNode = node; currentName = node.getNodeName(); boolean isNull = false; NamedNodeMap attrs = node.getAttributes(); String arrayType = null; for (int i = 0; i < attrs.getLength(); i++) { String nodeName = attrs.item(i).getNodeName(); String nodeValue = attrs.item(i).getNodeValue(); if (nodeName.equals(NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":" + Constants.ATTR_TYPE)) currentType = new StringBuffer(nodeValue).delete(0, nodeValue.indexOf(':') + 1).toString(); else if (nodeName.equals( NamespaceConstants.NSPREFIX_SOAP_ENCODING + ":" + Constants.ATTR_ARRAY_TYPE)) arrayType = new StringBuffer(nodeValue).delete(0, nodeValue.indexOf(':') + 1).toString(); else if (nodeName.equals(NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":null")) isNull = nodeValue.equals("true"); } Class cls = null; if (currentType != null) cls = getXsdTypeClass(currentType); // Handle array, Vector, ArrayList, LinkedList, Hashtable, // Properties, and HashMap data types if ((cls != null) && ((cls == java.lang.reflect.Array.class) || (cls == Vector.class) || (cls == ArrayList.class) || (cls == LinkedList.class) || (cls == Hashtable.class) || (cls == Properties.class) || (cls == HashMap.class) || (cls == SortedMap.class))) { parentNode = currentNode; String name = node.getNodeName(); // Handle arrays if (cls == java.lang.reflect.Array.class) { int a = arrayType.indexOf("["); int b = arrayType.indexOf("]"); String s = arrayType.substring(a + 1, b); int arrayLen = Integer.valueOf(s).intValue(); arrayType = arrayType.substring(0, a); // check if the array element is a standard Java class Class arrayClass = getXsdTypeClass(arrayType); // otherwise try to get the class of the bean if (arrayClass == null) arrayClass = getClassOfBean((ClassLoader) classLoaderStrategy, arrayType); object = java.lang.reflect.Array.newInstance(arrayClass, arrayLen); } else { // Construct the list or map type Constructor ct = cls.getConstructor((Class[]) null); object = ct.newInstance((Object[]) null); } // deserialize the elements of the array, list, or map NodeList childNodes = node.getChildNodes(); int arrayIndex = -1; Node childNode = null; Object nodeObj = null; for (int i = 0; i < childNodes.getLength(); i++) { childNode = childNodes.item(i); if (childNode.getNodeType() == Node.ELEMENT_NODE) { if ((cls == java.lang.reflect.Array.class) || (cls == Vector.class) || (cls == ArrayList.class) || (cls == LinkedList.class)) { nodeObj = deserialize(childNode, false, true); if (nodeObj != null) { if (cls == java.lang.reflect.Array.class) java.lang.reflect.Array.set(object, ++arrayIndex, nodeObj); else ((List) object).add(nodeObj); } } else if ((cls == Hashtable.class) || (cls == Properties.class) || (cls == HashMap.class) || (cls == SortedMap.class)) { if (childNode.getLocalName().equals("item")) { NodeList htNodes = childNode.getChildNodes(); if (htNodes.getLength() == 2) { Object hashKey = deserialize(htNodes.item(0), false, false); Object hashValue = deserialize(htNodes.item(1), false, true); ((Map) object).put(hashKey, hashValue); } } } } } setBeanProperty(name, object); // Handle everything else (primitives & POJOs) } else { // recurse on each of the child nodes NodeList childNodes = node.getChildNodes(); if ((childNodes != null) && (childNodes.getLength() > 0)) { for (int i = 0; i < childNodes.getLength(); i++) { Node childNode = childNodes.item(i); if (childNode.getNodeType() == Node.ELEMENT_NODE) { if (currentType != null) createObject( node, currentName, currentPackage, currentType, childNode.getNodeValue(), setProperty); parentNode = node; object = deserialize(childNode, true, true); } else if ((childNode.getNodeType() == Node.TEXT_NODE) && (currentType != null)) { object = createObject( node, currentName, currentPackage, currentType, childNode.getNodeValue(), setProperty); } currentType = null; } } else { if (!isNull) object = createObject(node, currentName, currentPackage, currentType, null, setProperty); } if (node.getParentNode() != parentNode) { parentNode = node.getParentNode(); if (popBean) { Object bean = popBeanOffStack(); if (bean != null) object = bean; } } } return object; }
/** * Parses object with follow rules: * * <p>1. All fields should had a public access. 2. The name of the filed should be fully equal to * name of JSONObject key. 3. Supports parse of all Java primitives, all {@link String}, arrays of * primitive types, {@link String}s and {@link com.vk.sdk.api.model.VKApiModel}s, list * implementation line {@link VKList}, {@link com.vk.sdk.api.model.VKAttachments.VKAttachment} or * {@link com.vk.sdk.api.model.VKPhotoSizes}, {@link com.vk.sdk.api.model.VKApiModel}s. * * <p>4. Boolean fields defines by vk_int == 1 expression. * * @param object object to initialize * @param source data to read values * @param <T> type of result * @return initialized according with given data object * @throws org.json.JSONException if source object structure is invalid */ @SuppressWarnings({"rawtypes", "unchecked"}) public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException { if (source.has("response")) { source = source.optJSONObject("response"); } if (source == null) { return object; } for (Field field : object.getClass().getFields()) { field.setAccessible(true); String fieldName = field.getName(); Class<?> fieldType = field.getType(); Object value = source.opt(fieldName); if (value == null) { continue; } try { if (fieldType.isPrimitive() && value instanceof Number) { Number number = (Number) value; if (fieldType.equals(int.class)) { field.setInt(object, number.intValue()); } else if (fieldType.equals(long.class)) { field.setLong(object, number.longValue()); } else if (fieldType.equals(float.class)) { field.setFloat(object, number.floatValue()); } else if (fieldType.equals(double.class)) { field.setDouble(object, number.doubleValue()); } else if (fieldType.equals(boolean.class)) { field.setBoolean(object, number.intValue() == 1); } else if (fieldType.equals(short.class)) { field.setShort(object, number.shortValue()); } else if (fieldType.equals(byte.class)) { field.setByte(object, number.byteValue()); } } else { Object result = field.get(object); if (value.getClass().equals(fieldType)) { result = value; } else if (fieldType.isArray() && value instanceof JSONArray) { result = parseArrayViaReflection((JSONArray) value, fieldType); } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) { Constructor<?> constructor = fieldType.getConstructor(JSONArray.class); result = constructor.newInstance((JSONArray) value); } else if (VKAttachments.class.isAssignableFrom(fieldType) && value instanceof JSONArray) { Constructor<?> constructor = fieldType.getConstructor(JSONArray.class); result = constructor.newInstance((JSONArray) value); } else if (VKList.class.equals(fieldType)) { ParameterizedType genericTypes = (ParameterizedType) field.getGenericType(); Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0]; if (VKApiModel.class.isAssignableFrom(genericType) && Parcelable.class.isAssignableFrom(genericType) && Identifiable.class.isAssignableFrom(genericType)) { if (value instanceof JSONArray) { result = new VKList((JSONArray) value, genericType); } else if (value instanceof JSONObject) { result = new VKList((JSONObject) value, genericType); } } } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) { result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value); } field.set(object, result); } } catch (InstantiationException e) { throw new JSONException(e.getMessage()); } catch (IllegalAccessException e) { throw new JSONException(e.getMessage()); } catch (NoSuchMethodException e) { throw new JSONException(e.getMessage()); } catch (InvocationTargetException e) { throw new JSONException(e.getMessage()); } catch (NoSuchMethodError e) { // Примечание Виталия: // Вы не поверите, но у некоторых вендоров getFields() вызывает ВОТ ЭТО. // Иногда я всерьез задумываюсь, правильно ли я поступил, выбрав Android в качестве // платформы разработки. throw new JSONException(e.getMessage()); } } return object; }
/** * Unmarshall a Chromosome instance from a given XML Element representation. * * @param a_activeConfiguration current Configuration object * @param a_xmlElement the XML Element representation of the Chromosome * @return a new Chromosome instance setup with the data from the XML Element representation * @throws ImproperXMLException if the given Element is improperly structured or missing data * @throws UnsupportedRepresentationException if the actively configured Gene implementation does * not support the string representation of the alleles used in the given XML document * @throws GeneCreationException if there is a problem creating or populating a Gene instance * @author Neil Rotstan * @since 1.0 */ public static Gene[] getGenesFromElement( Configuration a_activeConfiguration, Element a_xmlElement) throws ImproperXMLException, UnsupportedRepresentationException, GeneCreationException { // Do some sanity checking. Make sure the XML Element isn't null and // that it in fact represents a set of genes. // ----------------------------------------------------------------- if (a_xmlElement == null || !(a_xmlElement.getTagName().equals(GENES_TAG))) { throw new ImproperXMLException( "Unable to build Chromosome instance from XML Element: " + "given Element is not a 'genes' element."); } List genes = Collections.synchronizedList(new ArrayList()); // Extract the nested gene elements. // --------------------------------- NodeList geneElements = a_xmlElement.getElementsByTagName(GENE_TAG); if (geneElements == null) { throw new ImproperXMLException( "Unable to build Gene instances from XML Element: " + "'" + GENE_TAG + "'" + " sub-elements not found."); } // For each gene, get the class attribute so we know what class // to instantiate to represent the gene instance, and then find // the child text node, which is where the string representation // of the allele is located, and extract the representation. // ------------------------------------------------------------- int numberOfGeneNodes = geneElements.getLength(); for (int i = 0; i < numberOfGeneNodes; i++) { Element thisGeneElement = (Element) geneElements.item(i); thisGeneElement.normalize(); // Fetch the class attribute and create an instance of that // class to represent the current gene. // -------------------------------------------------------- String geneClassName = thisGeneElement.getAttribute(CLASS_ATTRIBUTE); Gene thisGeneObject; Class geneClass = null; try { geneClass = Class.forName(geneClassName); try { Constructor constr = geneClass.getConstructor(new Class[] {Configuration.class}); thisGeneObject = (Gene) constr.newInstance(new Object[] {a_activeConfiguration}); } catch (NoSuchMethodException nsme) { // Try it by calling method newGeneInternal. // ----------------------------------------- Constructor constr = geneClass.getConstructor(new Class[] {}); thisGeneObject = (Gene) constr.newInstance(new Object[] {}); thisGeneObject = (Gene) PrivateAccessor.invoke( thisGeneObject, "newGeneInternal", new Class[] {}, new Object[] {}); } } catch (Throwable e) { throw new GeneCreationException(geneClass, e); } // Find the text node and fetch the string representation of // the allele. // --------------------------------------------------------- NodeList children = thisGeneElement.getChildNodes(); int childrenSize = children.getLength(); String alleleRepresentation = null; for (int j = 0; j < childrenSize; j++) { Element alleleElem = (Element) children.item(j); if (alleleElem.getTagName().equals(ALLELE_TAG)) { alleleRepresentation = alleleElem.getAttribute("value"); } if (children.item(j).getNodeType() == Node.TEXT_NODE) { // We found the text node. Extract the representation. // --------------------------------------------------- alleleRepresentation = children.item(j).getNodeValue(); break; } } // Sanity check: Make sure the representation isn't null. // ------------------------------------------------------ if (alleleRepresentation == null) { throw new ImproperXMLException( "Unable to build Gene instance from XML Element: " + "value (allele) is missing representation."); } // Now set the value of the gene to that reflect the // string representation. // ------------------------------------------------- try { thisGeneObject.setValueFromPersistentRepresentation(alleleRepresentation); } catch (UnsupportedOperationException e) { throw new GeneCreationException( "Unable to build Gene because it does not support the " + "setValueFromPersistentRepresentation() method."); } // Finally, add the current gene object to the list of genes. // ---------------------------------------------------------- genes.add(thisGeneObject); } return (Gene[]) genes.toArray(new Gene[genes.size()]); }
static Object js_createAdapter(Context cx, Scriptable scope, Object[] args) { int N = args.length; if (N == 0) { throw ScriptRuntime.typeError0("msg.adapter.zero.args"); } // Expected arguments: // Any number of NativeJavaClass objects representing the super-class // and/or interfaces to implement, followed by one NativeObject providing // the implementation, followed by any number of arguments to pass on // to the (super-class) constructor. int classCount; for (classCount = 0; classCount < N - 1; classCount++) { Object arg = args[classCount]; // We explicitly test for NativeObject here since checking for // instanceof ScriptableObject or !(instanceof NativeJavaClass) // would fail for a Java class that isn't found in the class path // as NativeJavaPackage extends ScriptableObject. if (arg instanceof NativeObject) { break; } if (!(arg instanceof NativeJavaClass)) { throw ScriptRuntime.typeError2( "msg.not.java.class.arg", String.valueOf(classCount), ScriptRuntime.toString(arg)); } } Class<?> superClass = null; Class<?>[] intfs = new Class[classCount]; int interfaceCount = 0; for (int i = 0; i < classCount; ++i) { Class<?> c = ((NativeJavaClass) args[i]).getClassObject(); if (!c.isInterface()) { if (superClass != null) { throw ScriptRuntime.typeError2("msg.only.one.super", superClass.getName(), c.getName()); } superClass = c; } else { intfs[interfaceCount++] = c; } } if (superClass == null) { superClass = ScriptRuntime.ObjectClass; } Class<?>[] interfaces = new Class[interfaceCount]; System.arraycopy(intfs, 0, interfaces, 0, interfaceCount); // next argument is implementation, must be scriptable Scriptable obj = ScriptableObject.ensureScriptable(args[classCount]); Class<?> adapterClass = getAdapterClass(scope, superClass, interfaces, obj); Object adapter; int argsCount = N - classCount - 1; try { if (argsCount > 0) { // Arguments contain parameters for super-class constructor. // We use the generic Java method lookup logic to find and // invoke the right constructor. Object[] ctorArgs = new Object[argsCount + 2]; ctorArgs[0] = obj; ctorArgs[1] = cx.getFactory(); System.arraycopy(args, classCount + 1, ctorArgs, 2, argsCount); // TODO: cache class wrapper? NativeJavaClass classWrapper = new NativeJavaClass(scope, adapterClass, true); NativeJavaMethod ctors = classWrapper.members.ctors; int index = ctors.findCachedFunction(cx, ctorArgs); if (index < 0) { String sig = NativeJavaMethod.scriptSignature(args); throw Context.reportRuntimeError2("msg.no.java.ctor", adapterClass.getName(), sig); } // Found the constructor, so try invoking it. adapter = NativeJavaClass.constructInternal(ctorArgs, ctors.methods[index]); } else { Class<?>[] ctorParms = {ScriptRuntime.ScriptableClass, ScriptRuntime.ContextFactoryClass}; Object[] ctorArgs = {obj, cx.getFactory()}; adapter = adapterClass.getConstructor(ctorParms).newInstance(ctorArgs); } Object self = getAdapterSelf(adapterClass, adapter); // Return unwrapped JavaAdapter if it implements Scriptable if (self instanceof Wrapper) { Object unwrapped = ((Wrapper) self).unwrap(); if (unwrapped instanceof Scriptable) { if (unwrapped instanceof ScriptableObject) { ScriptRuntime.setObjectProtoAndParent((ScriptableObject) unwrapped, scope); } return unwrapped; } } return self; } catch (Exception ex) { throw Context.throwAsScriptRuntimeEx(ex); } }
public static void main(String[] args) { // Obtain the class object if we know the name of the class Class rental = RentCar.class; try { // get the absolute name of the class String rentalClassPackage = rental.getName(); System.out.println("Class Name is: " + rentalClassPackage); // get the simple name of the class (without package info) String rentalClassNoPackage = rental.getSimpleName(); System.out.println("Class Name without package is: " + rentalClassNoPackage); // get the package name of the class Package rentalPackage = rental.getPackage(); System.out.println("Package Name is: " + rentalPackage); // get all the constructors of the class Constructor[] constructors = rental.getConstructors(); System.out.println("Constructors are: " + Arrays.toString(constructors)); // get constructor with specific argument Constructor constructor = rental.getConstructor(Integer.TYPE); // initializing an object of the RentCar class RentCar rent = (RentCar) constructor.newInstance(455); // get all methods of the class including declared methods of // superclasses // in that case, superclass of RentCar is the class java.lang.Object Method[] allmethods = rental.getMethods(); System.out.println("Methods are: " + Arrays.toString(allmethods)); for (Method method : allmethods) { System.out.println("method = " + method.getName()); } // get all methods declared in the class // but excludes inherited methods. Method[] declaredMethods = rental.getDeclaredMethods(); System.out.println("Declared Methods are: " + Arrays.toString(declaredMethods)); for (Method dmethod : declaredMethods) { System.out.println("method = " + dmethod.getName()); } // get method with specific name and parameters Method oneMethod = rental.getMethod("computeRentalCost", new Class[] {Integer.TYPE}); System.out.println("Method is: " + oneMethod); // call computeRentalCost method with parameter int oneMethod.invoke(rent, 4); // get all the parameters of computeRentalCost Class[] parameterTypes = oneMethod.getParameterTypes(); System.out.println( "Parameter types of computeRentalCost() are: " + Arrays.toString(parameterTypes)); // get the return type of computeRentalCost Class returnType = oneMethod.getReturnType(); System.out.println("Return type is: " + returnType); // gets all the public member fields of the class RentCar Field[] fields = rental.getFields(); System.out.println("Public Fields are: "); for (Field oneField : fields) { // get public field name Field field = rental.getField(oneField.getName()); String fieldname = field.getName(); System.out.println("Fieldname is: " + fieldname); // get public field type Object fieldType = field.getType(); System.out.println("Type of field " + fieldname + " is: " + fieldType); // get public field value Object value = field.get(rent); System.out.println("Value of field " + fieldname + " is: " + value); } // How to access private member fields of the class // getDeclaredField() returns the private field Field privateField = RentCar.class.getDeclaredField("type"); String name = privateField.getName(); System.out.println("One private Fieldname is: " + name); // makes this private field instance accessible // for reflection use only, not normal code privateField.setAccessible(true); // get the value of this private field String fieldValue = (String) privateField.get(rent); System.out.println("fieldValue = " + fieldValue); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } }
static Provider getSunPKCS11(String config) throws Exception { Class clazz = Class.forName("sun.security.pkcs11.SunPKCS11"); Constructor cons = clazz.getConstructor(new Class[] {String.class}); Object obj = cons.newInstance(new Object[] {config}); return (Provider) obj; }
public static void main(String[] args) throws Exception { System.out.println( "Checking that all known MBeans that are " + "NotificationBroadcasters have sane " + "MBeanInfo.getNotifications()"); System.out.println("Checking platform MBeans..."); checkPlatformMBeans(); URL codeBase = ClassLoader.getSystemResource("javax/management/MBeanServer.class"); if (codeBase == null) { throw new Exception("Could not determine codeBase for " + MBeanServer.class); } System.out.println(); System.out.println("Looking for standard MBeans..."); String[] classes = findStandardMBeans(codeBase); System.out.println("Testing standard MBeans..."); for (int i = 0; i < classes.length; i++) { String name = classes[i]; Class<?> c; try { c = Class.forName(name); } catch (Throwable e) { System.out.println(name + ": cannot load (not public?): " + e); continue; } if (!NotificationBroadcaster.class.isAssignableFrom(c)) { System.out.println(name + ": not a NotificationBroadcaster"); continue; } if (Modifier.isAbstract(c.getModifiers())) { System.out.println(name + ": abstract class"); continue; } NotificationBroadcaster mbean; Constructor<?> constr; try { constr = c.getConstructor(); } catch (Exception e) { System.out.println(name + ": no public no-arg constructor: " + e); continue; } try { mbean = (NotificationBroadcaster) constr.newInstance(); } catch (Exception e) { System.out.println(name + ": no-arg constructor failed: " + e); continue; } check(mbean); } System.out.println(); System.out.println("Testing some explicit cases..."); check(new RelationService(false)); /* We can't do this: check(new RequiredModelMBean()); because the Model MBean spec more or less forces us to use the names GENERIC and ATTRIBUTE_CHANGE for its standard notifs. */ checkRMIConnectorServer(); System.out.println(); if (!suspicious.isEmpty()) System.out.println("SUSPICIOUS CLASSES: " + suspicious); if (failed.isEmpty()) System.out.println("TEST PASSED"); else { System.out.println("TEST FAILED: " + failed); System.exit(1); } }