Ejemplo n.º 1
0
        private Object ApplyGetters(Object target, String getters)
        {
            if (getters == null || getters.Equals(""))
            {
                return(target);
            }
            int firstDot = getters.IndexOf('.');

            if (firstDot == -1)
            {
                firstDot = getters.Length();
            }
            String first = getters.Substring(0, firstDot);
            String rest  = getters.Substring(System.Math.Min(firstDot + 1, getters.Length()));

            try
            {
                Method getter = null;
                if (target != null)
                {
                    getter = Statement.GetMethod(target.GetType(), "get" + NameGenerator.Capitalize(first), new Class[] {});
                    if (getter == null)
                    {
                        getter = Statement.GetMethod(target.GetType(), "is" + NameGenerator.Capitalize(first), new Class[] {});
                    }
                    if (getter == null)
                    {
                        getter = Statement.GetMethod(target.GetType(), first, new Class[] {});
                    }
                }
                if (getter == null)
                {
                    throw new RuntimeException("No method called: " + first + " defined on " + target);
                }
                Object newTarget = MethodUtil.invoke(getter, target, new Object[] {});
                return(ApplyGetters(newTarget, rest));
            }
            catch (Exception e)
            {
                throw new RuntimeException("Failed to call method: " + first + " on " + target, e);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// This default implementation of the <code>instantiate</code> method returns
        /// an expression containing the predefined method name "new" which denotes a
        /// call to a constructor with the arguments as specified in
        /// the <code>DefaultPersistenceDelegate</code>'s constructor.
        /// </summary>
        /// <param name="oldInstance"> The instance to be instantiated. </param>
        /// <param name="out"> The code output stream. </param>
        /// <returns> An expression whose value is <code>oldInstance</code>.
        /// </returns>
        /// <exception cref="NullPointerException"> if {@code out} is {@code null}
        ///                              and this value is used in the method
        /// </exception>
        /// <seealso cref= #DefaultPersistenceDelegate(String[]) </seealso>
        protected internal override Expression Instantiate(Object oldInstance, Encoder @out)
        {
            int   nArgs = Constructor.Length;
            Class type  = oldInstance.GetType();

            Object[] constructorArgs = new Object[nArgs];
            for (int i = 0; i < nArgs; i++)
            {
                try
                {
                    Method method = FindMethod(type, this.Constructor[i]);
                    constructorArgs[i] = MethodUtil.invoke(method, oldInstance, new Object[0]);
                }
                catch (Exception e)
                {
                    @out.ExceptionListener.ExceptionThrown(e);
                }
            }
            return(new Expression(oldInstance, oldInstance.GetType(), "new", constructorArgs));
        }
Ejemplo n.º 3
0
        private Object InvokeInternal(Object proxy, Method method, Object[] arguments)
        {
            String methodName = method.Name;

            if (method.DeclaringClass == typeof(Object))
            {
                // Handle the Object public methods.
                if (methodName.Equals("hashCode"))
                {
                    return(new Integer(System.identityHashCode(proxy)));
                }
                else if (methodName.Equals("equals"))
                {
                    return(proxy == arguments[0] ? true : false);
                }
                else if (methodName.Equals("toString"))
                {
//JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method:
                    return(proxy.GetType().FullName + '@' + proxy.HashCode().ToString("x"));
                }
            }

            if (ListenerMethodName_Renamed == null || ListenerMethodName_Renamed.Equals(methodName))
            {
                Class[]  argTypes = null;
                Object[] newArgs  = null;

                if (EventPropertyName_Renamed == null)                 // Nullary method.
                {
                    newArgs  = new Object[] {};
                    argTypes = new Class[] {};
                }
                else
                {
                    Object input = ApplyGetters(arguments[0], EventPropertyName);
                    newArgs  = new Object[] { input };
                    argTypes = new Class[] { input == null ? null : input.GetType() };
                }
                try
                {
                    int lastDot = Action_Renamed.LastIndexOf('.');
                    if (lastDot != -1)
                    {
                        Target_Renamed = ApplyGetters(Target_Renamed, Action_Renamed.Substring(0, lastDot));
                        Action_Renamed = Action_Renamed.Substring(lastDot + 1);
                    }
                    Method targetMethod = Statement.GetMethod(Target_Renamed.GetType(), Action_Renamed, argTypes);
                    if (targetMethod == null)
                    {
                        targetMethod = Statement.GetMethod(Target_Renamed.GetType(), "set" + NameGenerator.Capitalize(Action_Renamed), argTypes);
                    }
                    if (targetMethod == null)
                    {
                        String argTypeString = (argTypes.Length == 0) ? " with no arguments" : " with argument " + argTypes[0];
                        throw new RuntimeException("No method called " + Action_Renamed + " on " + Target_Renamed.GetType() + argTypeString);
                    }
                    return(MethodUtil.invoke(targetMethod, Target_Renamed, newArgs));
                }
                catch (IllegalAccessException ex)
                {
                    throw new RuntimeException(ex);
                }
                catch (InvocationTargetException ex)
                {
                    Throwable th = ex.TargetException;
                    throw (th is RuntimeException) ? (RuntimeException)th : new RuntimeException(th);
                }
            }
            return(null);
        }
Ejemplo n.º 4
0
        // Write out the properties of this instance.
        private void InitBean(Class type, Object oldInstance, Object newInstance, Encoder @out)
        {
            foreach (Field field in type.Fields)
            {
                if (!ReflectUtil.isPackageAccessible(field.DeclaringClass))
                {
                    continue;
                }
                int mod = field.Modifiers;
                if (Modifier.IsFinal(mod) || Modifier.IsStatic(mod) || Modifier.IsTransient(mod))
                {
                    continue;
                }
                try
                {
                    Expression oldGetExp = new Expression(field, "get", new Object[] { oldInstance });
                    Expression newGetExp = new Expression(field, "get", new Object[] { newInstance });
                    Object     oldValue  = oldGetExp.Value;
                    Object     newValue  = newGetExp.Value;
                    @out.WriteExpression(oldGetExp);
                    if (!Objects.Equals(newValue, @out.Get(oldValue)))
                    {
                        @out.WriteStatement(new Statement(field, "set", new Object[] { oldInstance, oldValue }));
                    }
                }
                catch (Exception exception)
                {
                    @out.ExceptionListener.ExceptionThrown(exception);
                }
            }
            BeanInfo info;

            try
            {
                info = Introspector.GetBeanInfo(type);
            }
            catch (IntrospectionException)
            {
                return;
            }
            // Properties
            foreach (PropertyDescriptor d in info.PropertyDescriptors)
            {
                if (d.IsTransient())
                {
                    continue;
                }
                try
                {
                    DoProperty(type, d, oldInstance, newInstance, @out);
                }
                catch (Exception e)
                {
                    @out.ExceptionListener.ExceptionThrown(e);
                }
            }

            // Listeners

            /*
             * Pending(milne). There is a general problem with the archival of
             * listeners which is unresolved as of 1.4. Many of the methods
             * which install one object inside another (typically "add" methods
             * or setters) automatically install a listener on the "child" object
             * so that its "parent" may respond to changes that are made to it.
             * For example the JTable:setModel() method automatically adds a
             * TableModelListener (the JTable itself in this case) to the supplied
             * table model.
             *
             * We do not need to explicitly add these listeners to the model in an
             * archive as they will be added automatically by, in the above case,
             * the JTable's "setModel" method. In some cases, we must specifically
             * avoid trying to do this since the listener may be an inner class
             * that cannot be instantiated using public API.
             *
             * No general mechanism currently
             * exists for differentiating between these kind of listeners and
             * those which were added explicitly by the user. A mechanism must
             * be created to provide a general means to differentiate these
             * special cases so as to provide reliable persistence of listeners
             * for the general case.
             */
            if (!type.IsSubclassOf(typeof(java.awt.Component)))
            {
                return;                 // Just handle the listeners of Components for now.
            }
            foreach (EventSetDescriptor d in info.EventSetDescriptors)
            {
                if (d.IsTransient())
                {
                    continue;
                }
                Class listenerType = d.ListenerType;


                // The ComponentListener is added automatically, when
                // Contatiner:add is called on the parent.
                if (listenerType == typeof([email protected]))
                {
                    continue;
                }

                // JMenuItems have a change listener added to them in
                // their "add" methods to enable accessibility support -
                // see the add method in JMenuItem for details. We cannot
                // instantiate this instance as it is a private inner class
                // and do not need to do this anyway since it will be created
                // and installed by the "add" method. Special case this for now,
                // ignoring all change listeners on JMenuItems.
                if (listenerType == typeof([email protected]) && type == typeof(javax.swing.JMenuItem))
                {
                    continue;
                }

                EventListener[] oldL = new EventListener[0];
                EventListener[] newL = new EventListener[0];
                try
                {
                    Method m = d.GetListenerMethod;
                    oldL = (EventListener[])MethodUtil.invoke(m, oldInstance, new Object[] {});
                    newL = (EventListener[])MethodUtil.invoke(m, newInstance, new Object[] {});
                }
                catch (Exception)
                {
                    try
                    {
                        Method m = type.GetMethod("getListeners", new Class[] { typeof(Class) });
                        oldL = (EventListener[])MethodUtil.invoke(m, oldInstance, new Object[] { listenerType });
                        newL = (EventListener[])MethodUtil.invoke(m, newInstance, new Object[] { listenerType });
                    }
                    catch (Exception)
                    {
                        return;
                    }
                }

                // Asssume the listeners are in the same order and that there are no gaps.
                // Eventually, this may need to do true differencing.
                String addListenerMethodName = d.AddListenerMethod.Name;
                for (int i = newL.Length; i < oldL.Length; i++)
                {
                    // System.out.println("Adding listener: " + addListenerMethodName + oldL[i]);
                    InvokeStatement(oldInstance, addListenerMethodName, new Object[] { oldL[i] }, @out);
                }

                String removeListenerMethodName = d.RemoveListenerMethod.Name;
                for (int i = oldL.Length; i < newL.Length; i++)
                {
                    InvokeStatement(oldInstance, removeListenerMethodName, new Object[] { newL[i] }, @out);
                }
            }
        }
Ejemplo n.º 5
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private Object invokeInternal() throws Exception
        private Object InvokeInternal()
        {
            Object target     = Target;
            String methodName = MethodName;

            if (target == null || methodName == null)
            {
                throw new NullPointerException((target == null ? "target" : "methodName") + " should not be null");
            }

            Object[] arguments = Arguments;
            if (arguments == null)
            {
                arguments = EmptyArray;
            }
            // Class.forName() won't load classes outside
            // of core from a class inside core. Special
            // case this method.
            if (target == typeof(Class) && methodName.Equals("forName"))
            {
                return(ClassFinder.resolveClass((String)arguments[0], this.Loader));
            }
            Class[] argClasses = new Class[arguments.Length];
            for (int i = 0; i < arguments.Length; i++)
            {
                argClasses[i] = (arguments[i] == null) ? null : arguments[i].GetType();
            }

            AccessibleObject m = null;

            if (target is Class)
            {
                /*
                 * For class methods, simluate the effect of a meta class
                 * by taking the union of the static methods of the
                 * actual class, with the instance methods of "Class.class"
                 * and the overloaded "newInstance" methods defined by the
                 * constructors.
                 * This way "System.class", for example, will perform both
                 * the static method getProperties() and the instance method
                 * getSuperclass() defined in "Class.class".
                 */
                if (methodName.Equals("new"))
                {
                    methodName = "newInstance";
                }
                // Provide a short form for array instantiation by faking an nary-constructor.
                if (methodName.Equals("newInstance") && ((Class)target).Array)
                {
                    Object result = Array.newInstance(((Class)target).ComponentType, arguments.Length);
                    for (int i = 0; i < arguments.Length; i++)
                    {
                        Array.set(result, i, arguments[i]);
                    }
                    return(result);
                }
                if (methodName.Equals("newInstance") && arguments.Length != 0)
                {
                    // The Character class, as of 1.4, does not have a constructor
                    // which takes a String. All of the other "wrapper" classes
                    // for Java's primitive types have a String constructor so we
                    // fake such a constructor here so that this special case can be
                    // ignored elsewhere.
                    if (target == typeof(Character) && arguments.Length == 1 && argClasses[0] == typeof(String))
                    {
                        return(new Character(((String)arguments[0]).CharAt(0)));
                    }
                    try
                    {
                        m = ConstructorFinder.findConstructor((Class)target, argClasses);
                    }
                    catch (NoSuchMethodException)
                    {
                        m = null;
                    }
                }
                if (m == null && target != typeof(Class))
                {
                    m = GetMethod((Class)target, methodName, argClasses);
                }
                if (m == null)
                {
                    m = GetMethod(typeof(Class), methodName, argClasses);
                }
            }
            else
            {
                /*
                 * This special casing of arrays is not necessary, but makes files
                 * involving arrays much shorter and simplifies the archiving infrastrcure.
                 * The Array.set() method introduces an unusual idea - that of a static method
                 * changing the state of an instance. Normally statements with side
                 * effects on objects are instance methods of the objects themselves
                 * and we reinstate this rule (perhaps temporarily) by special-casing arrays.
                 */
                if (target.GetType().IsArray&& (methodName.Equals("set") || methodName.Equals("get")))
                {
                    int index = ((Integer)arguments[0]).IntValue();
                    if (methodName.Equals("get"))
                    {
                        return(Array.get(target, index));
                    }
                    else
                    {
                        Array.set(target, index, arguments[1]);
                        return(null);
                    }
                }
                m = GetMethod(target.GetType(), methodName, argClasses);
            }
            if (m != null)
            {
                try
                {
                    if (m is Method)
                    {
                        return(MethodUtil.invoke((Method)m, target, arguments));
                    }
                    else
                    {
                        return(((Constructor)m).newInstance(arguments));
                    }
                }
                catch (IllegalAccessException iae)
                {
                    throw new Exception("Statement cannot invoke: " + methodName + " on " + target.GetType(), iae);
                }
                catch (InvocationTargetException ite)
                {
                    Throwable te = ite.TargetException;
                    if (te is Exception)
                    {
                        throw (Exception)te;
                    }
                    else
                    {
                        throw ite;
                    }
                }
            }
            throw new NoSuchMethodException(ToString());
        }