Statement.java 13.2 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright 2000-2010 Sun Microsystems, Inc.  All Rights Reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Sun designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Sun in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
 * CA 95054 USA or visit www.sun.com if you need additional information or
 * have any questions.
 */
package java.beans;

import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.sun.beans.finder.ClassFinder;
34 35
import com.sun.beans.finder.ConstructorFinder;
import com.sun.beans.finder.MethodFinder;
D
duke 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
import sun.reflect.misc.MethodUtil;

/**
 * A <code>Statement</code> object represents a primitive statement
 * in which a single method is applied to a target and
 * a set of arguments - as in <code>"a.setFoo(b)"</code>.
 * Note that where this example uses names
 * to denote the target and its argument, a statement
 * object does not require a name space and is constructed with
 * the values themselves.
 * The statement object associates the named method
 * with its environment as a simple set of values:
 * the target and an array of argument values.
 *
 * @since 1.4
 *
 * @author Philip Milne
 */
public class Statement {

    private static Object[] emptyArray = new Object[]{};

    static ExceptionListener defaultExceptionListener = new ExceptionListener() {
        public void exceptionThrown(Exception e) {
            System.err.println(e);
            // e.printStackTrace();
            System.err.println("Continuing ...");
        }
    };

    Object target;
    String methodName;
    Object[] arguments;
69
    ClassLoader loader;
D
duke 已提交
70 71

    /**
72 73 74 75 76 77 78 79 80
     * Creates a new {@link Statement} object
     * for the specified target object to invoke the method
     * specified by the name and by the array of arguments.
     * <p>
     * The {@code target} and the {@code methodName} values should not be {@code null}.
     * Otherwise an attempt to execute this {@code Expression}
     * will result in a {@code NullPointerException}.
     * If the {@code arguments} value is {@code null},
     * an empty array is used as the value of the {@code arguments} property.
D
duke 已提交
81
     *
82 83 84
     * @param target  the target object of this statement
     * @param methodName  the name of the method to invoke on the specified target
     * @param arguments  the array of arguments to invoke the specified method
D
duke 已提交
85 86 87 88 89 90 91 92 93
     */
    @ConstructorProperties({"target", "methodName", "arguments"})
    public Statement(Object target, String methodName, Object[] arguments) {
        this.target = target;
        this.methodName = methodName;
        this.arguments = (arguments == null) ? emptyArray : arguments;
    }

    /**
94 95 96 97
     * Returns the target object of this statement.
     * If this method returns {@code null},
     * the {@link #execute} method
     * throws a {@code NullPointerException}.
D
duke 已提交
98
     *
99
     * @return the target object of this statement
D
duke 已提交
100 101 102 103 104 105
     */
    public Object getTarget() {
        return target;
    }

    /**
106 107 108 109
     * Returns the name of the method to invoke.
     * If this method returns {@code null},
     * the {@link #execute} method
     * throws a {@code NullPointerException}.
D
duke 已提交
110
     *
111
     * @return the name of the method
D
duke 已提交
112 113 114 115 116 117
     */
    public String getMethodName() {
        return methodName;
    }

    /**
118 119 120 121
     * Returns the arguments for the method to invoke.
     * The number of arguments and their types
     * must match the method being  called.
     * {@code null} can be used as a synonym of an empty array.
D
duke 已提交
122
     *
123
     * @return the array of arguments
D
duke 已提交
124 125 126 127 128 129
     */
    public Object[] getArguments() {
        return arguments;
    }

    /**
130 131
     * The {@code execute} method finds a method whose name is the same
     * as the {@code methodName} property, and invokes the method on
D
duke 已提交
132 133 134 135 136 137 138
     * the target.
     *
     * When the target's class defines many methods with the given name
     * the implementation should choose the most specific method using
     * the algorithm specified in the Java Language Specification
     * (15.11). The dynamic class of the target and arguments are used
     * in place of the compile-time type information and, like the
139
     * {@link java.lang.reflect.Method} class itself, conversion between
D
duke 已提交
140 141 142 143 144 145 146 147 148 149
     * primitive values and their associated wrapper classes is handled
     * internally.
     * <p>
     * The following method types are handled as special cases:
     * <ul>
     * <li>
     * Static methods may be called by using a class object as the target.
     * <li>
     * The reserved method name "new" may be used to call a class's constructor
     * as if all classes defined static "new" methods. Constructor invocations
150
     * are typically considered {@code Expression}s rather than {@code Statement}s
D
duke 已提交
151 152
     * as they return a value.
     * <li>
153
     * The method names "get" and "set" defined in the {@link java.util.List}
D
duke 已提交
154
     * interface may also be applied to array instances, mapping to
155
     * the static methods of the same name in the {@code Array} class.
D
duke 已提交
156
     * </ul>
157 158 159 160 161 162 163 164 165
     *
     * @throws NullPointerException if the value of the {@code target} or
     *                              {@code methodName} property is {@code null}
     * @throws NoSuchMethodException if a matching method is not found
     * @throws SecurityException if a security manager exists and
     *                           it denies the method invocation
     * @throws Exception that is thrown by the invoked method
     *
     * @see java.lang.reflect.Method
D
duke 已提交
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
     */
    public void execute() throws Exception {
        invoke();
    }

    Object invoke() throws Exception {
        Object target = getTarget();
        String methodName = getMethodName();

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

        Object[] arguments = getArguments();
181 182 183
        if (arguments == null) {
            arguments = emptyArray;
        }
D
duke 已提交
184 185 186 187
        // Class.forName() won't load classes outside
        // of core from a class inside core. Special
        // case this method.
        if (target == Class.class && methodName.equals("forName")) {
188
            return ClassFinder.resolveClass((String)arguments[0], this.loader);
D
duke 已提交
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
        }
        Class[] argClasses = new Class[arguments.length];
        for(int i = 0; i < arguments.length; i++) {
            argClasses[i] = (arguments[i] == null) ? null : arguments[i].getClass();
        }

        AccessibleObject m = null;
        if (target instanceof 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).isArray()) {
                Object result = Array.newInstance(((Class)target).getComponentType(), 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 == Character.class && arguments.length == 1 &&
                    argClasses[0] == String.class) {
                    return new Character(((String)arguments[0]).charAt(0));
                }
228 229 230 231 232 233
                try {
                    m = ConstructorFinder.findConstructor((Class)target, argClasses);
                }
                catch (NoSuchMethodException exception) {
                    m = null;
                }
D
duke 已提交
234 235
            }
            if (m == null && target != Class.class) {
236
                m = getMethod((Class)target, methodName, argClasses);
D
duke 已提交
237 238
            }
            if (m == null) {
239
                m = getMethod(Class.class, methodName, argClasses);
D
duke 已提交
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
            }
        }
        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.getClass().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;
                }
            }
262
            m = getMethod(target.getClass(), methodName, argClasses);
D
duke 已提交
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
        }
        if (m != null) {
            try {
                if (m instanceof 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.getClass(),
                                    iae);
            }
            catch (InvocationTargetException ite) {
                Throwable te = ite.getTargetException();
                if (te instanceof Exception) {
                    throw (Exception)te;
                }
                else {
                    throw ite;
                }
            }
        }
        throw new NoSuchMethodException(toString());
    }

    String instanceName(Object instance) {
        if (instance == null) {
            return "null";
        } else if (instance.getClass() == String.class) {
            return "\""+(String)instance + "\"";
        } else {
            // Note: there is a minor problem with using the non-caching
            // NameGenerator method. The return value will not have
            // specific information about the inner class name. For example,
            // In 1.4.2 an inner class would be represented as JList$1 now
            // would be named Class.

            return NameGenerator.unqualifiedClassName(instance.getClass());
        }
    }

    /**
     * Prints the value of this statement using a Java-style syntax.
     */
    public String toString() {
        // Respect a subclass's implementation here.
        Object target = getTarget();
        String methodName = getMethodName();
        Object[] arguments = getArguments();
315 316 317
        if (arguments == null) {
            arguments = emptyArray;
        }
D
duke 已提交
318 319 320 321 322 323 324 325 326 327 328
        StringBuffer result = new StringBuffer(instanceName(target) + "." + methodName + "(");
        int n = arguments.length;
        for(int i = 0; i < n; i++) {
            result.append(instanceName(arguments[i]));
            if (i != n -1) {
                result.append(", ");
            }
        }
        result.append(");");
        return result.toString();
    }
329 330 331 332 333 334 335 336 337

    static Method getMethod(Class<?> type, String name, Class<?>... args) {
        try {
            return MethodFinder.findMethod(type, name, args);
        }
        catch (NoSuchMethodException exception) {
            return null;
        }
    }
D
duke 已提交
338
}