Debian Codegraph @

rhino/src/org/mozilla/javascript/NativeJavaClass.java

raw symbols SCIP
1 /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 package org.mozilla.javascript;
8
9 import java.lang.reflect.*;
10 import java.util.Map;
11
12 /**
13 * This class reflects Java classes into the JavaScript environment, mainly
14 * for constructors and static members. We lazily reflect properties,
15 * and currently do not guarantee that a single j.l.Class is only
16 * reflected once into the JS environment, although we should.
17 * The only known case where multiple reflections
18 * are possible occurs when a j.l.Class is wrapped as part of a
19 * method return or property access, rather than by walking the
20 * Packages/java tree.
21 *
22 * @author Mike Shaver
23 * @see NativeJavaArray
24 * @see NativeJavaObject
25 * @see NativeJavaPackage
26 */
27
28 public class NativeJavaClass extends NativeJavaObject implements Function
29 {
30 static final long serialVersionUID = -6460763940409461664L;
31
32 // Special property for getting the underlying Java class object.
33 static final String javaClassPropertyName = "__javaObject__";
34
35 public NativeJavaClass() {
36 }
37
38 public NativeJavaClass(Scriptable scope, Class<?> cl) {
39 this(scope, cl, false);
40 }
41
42 public NativeJavaClass(Scriptable scope, Class<?> cl, boolean isAdapter) {
43 super(scope, cl, null, isAdapter);
44 }
45
46 @Override
47 protected void initMembers() {
48 Class<?> cl = (Class<?>)javaObject;
49 members = JavaMembers.lookupClass(parent, cl, cl, isAdapter);
50 staticFieldAndMethods = members.getFieldAndMethodsObjects(this, cl, true);
51 }
52
53 @Override
54 public String getClassName() {
55 return "JavaClass";
56 }
57
58 @Override
59 public boolean has(String name, Scriptable start) {
60 return members.has(name, true) || javaClassPropertyName.equals(name);
61 }
62
63 @Override
64 public Object get(String name, Scriptable start) {
65 // When used as a constructor, ScriptRuntime.newObject() asks
66 // for our prototype to create an object of the correct type.
67 // We don't really care what the object is, since we're returning
68 // one constructed out of whole cloth, so we return null.
69 if (name.equals("prototype"))
70 return null;
71
72 if (staticFieldAndMethods != null) {
73 Object result = staticFieldAndMethods.get(name);
74 if (result != null)
75 return result;
76 }
77
78 if (members.has(name, true)) {
79 return members.get(this, name, javaObject, true);
80 }
81
82 Context cx = Context.getContext();
83 Scriptable scope = ScriptableObject.getTopLevelScope(start);
84 WrapFactory wrapFactory = cx.getWrapFactory();
85
86 if (javaClassPropertyName.equals(name)) {
87 return wrapFactory.wrap(cx, scope, javaObject,
88 ScriptRuntime.ClassClass);
89 }
90
91 // experimental: look for nested classes by appending $name to
92 // current class' name.
93 Class<?> nestedClass = findNestedClass(getClassObject(), name);
94 if (nestedClass != null) {
95 Scriptable nestedValue = wrapFactory.wrapJavaClass(cx, scope,
96 nestedClass);
97 nestedValue.setParentScope(this);
98 return nestedValue;
99 }
100
101 throw members.reportMemberNotFound(name);
102 }
103
104 @Override
105 public void put(String name, Scriptable start, Object value) {
106 members.put(this, name, javaObject, value, true);
107 }
108
109 @Override
110 public Object[] getIds() {
111 return members.getIds(true);
112 }
113
114 public Class<?> getClassObject() {
115 return (Class<?>) super.unwrap();
116 }
117
118 @Override
119 public Object getDefaultValue(Class<?> hint) {
120 if (hint == null || hint == ScriptRuntime.StringClass)
121 return this.toString();
122 if (hint == ScriptRuntime.BooleanClass)
123 return Boolean.TRUE;
124 if (hint == ScriptRuntime.NumberClass)
125 return ScriptRuntime.NaNobj;
126 return this;
127 }
128
129 public Object call(Context cx, Scriptable scope, Scriptable thisObj,
130 Object[] args)
131 {
132 // If it looks like a "cast" of an object to this class type,
133 // walk the prototype chain to see if there's a wrapper of a
134 // object that's an instanceof this class.
135 if (args.length == 1 && args[0] instanceof Scriptable) {
136 Class<?> c = getClassObject();
137 Scriptable p = (Scriptable) args[0];
138 do {
139 if (p instanceof Wrapper) {
140 Object o = ((Wrapper) p).unwrap();
141 if (c.isInstance(o))
142 return p;
143 }
144 p = p.getPrototype();
145 } while (p != null);
146 }
147 return construct(cx, scope, args);
148 }
149
150 public Scriptable construct(Context cx, Scriptable scope, Object[] args)
151 {
152 Class<?> classObject = getClassObject();
153 int modifiers = classObject.getModifiers();
154 if (! (Modifier.isInterface(modifiers) ||
155 Modifier.isAbstract(modifiers)))
156 {
157 NativeJavaMethod ctors = members.ctors;
158 int index = ctors.findCachedFunction(cx, args);
159 if (index < 0) {
160 String sig = NativeJavaMethod.scriptSignature(args);
161 throw Context.reportRuntimeError2(
162 "msg.no.java.ctor", classObject.getName(), sig);
163 }
164
165 // Found the constructor, so try invoking it.
166 return constructSpecific(cx, scope, args, ctors.methods[index]);
167 } else {
168 if (args.length == 0) {
169 throw Context.reportRuntimeError0("msg.adapter.zero.args");
170 }
171 Scriptable topLevel = ScriptableObject.getTopLevelScope(this);
172 String msg = "";
173 try {
174 // When running on Android create an InterfaceAdapter since our
175 // bytecode generation won't work on Dalvik VM.
176 if ("Dalvik".equals(System.getProperty("java.vm.name"))
177 && classObject.isInterface()) {
178 Object obj = createInterfaceAdapter(classObject,
179 ScriptableObject.ensureScriptableObject(args[0]));
180 return cx.getWrapFactory().wrapAsJavaObject(cx, scope, obj, null);
181 }
182 // use JavaAdapter to construct a new class on the fly that
183 // implements/extends this interface/abstract class.
184 Object v = topLevel.get("JavaAdapter", topLevel);
185 if (v != NOT_FOUND) {
186 Function f = (Function) v;
187 // Args are (interface, js object)
188 Object[] adapterArgs = { this, args[0] };
189 return f.construct(cx, topLevel, adapterArgs);
190 }
191 } catch (Exception ex) {
192 // fall through to error
193 String m = ex.getMessage();
194 if (m != null)
195 msg = m;
196 }
197 throw Context.reportRuntimeError2(
198 "msg.cant.instantiate", msg, classObject.getName());
199 }
200 }
201
202 static Scriptable constructSpecific(Context cx, Scriptable scope,
203 Object[] args, MemberBox ctor)
204 {
205 Object instance = constructInternal(args, ctor);
206 // we need to force this to be wrapped, because construct _has_
207 // to return a scriptable
208 Scriptable topLevel = ScriptableObject.getTopLevelScope(scope);
209 return cx.getWrapFactory().wrapNewObject(cx, topLevel, instance);
210 }
211
212 static Object constructInternal(Object[] args, MemberBox ctor)
213 {
214 Class<?>[] argTypes = ctor.argTypes;
215
216 if (ctor.vararg) {
217 // marshall the explicit parameter
218 Object[] newArgs = new Object[argTypes.length];
219 for (int i = 0; i < argTypes.length-1; i++) {
220 newArgs[i] = Context.jsToJava(args[i], argTypes[i]);
221 }
222
223 Object varArgs;
224
225 // Handle special situation where a single variable parameter
226 // is given and it is a Java or ECMA array.
227 if (args.length == argTypes.length &&
228 (args[args.length-1] == null ||
229 args[args.length-1] instanceof NativeArray ||
230 args[args.length-1] instanceof NativeJavaArray))
231 {
232 // convert the ECMA array into a native array
233 varArgs = Context.jsToJava(args[args.length-1],
234 argTypes[argTypes.length - 1]);
235 } else {
236 // marshall the variable parameter
237 Class<?> componentType = argTypes[argTypes.length - 1].
238 getComponentType();
239 varArgs = Array.newInstance(componentType,
240 args.length - argTypes.length + 1);
241 for (int i=0; i < Array.getLength(varArgs); i++) {
242 Object value = Context.jsToJava(args[argTypes.length-1 + i],
243 componentType);
244 Array.set(varArgs, i, value);
245 }
246 }
247
248 // add varargs
249 newArgs[argTypes.length-1] = varArgs;
250 // replace the original args with the new one
251 args = newArgs;
252 } else {
253 Object[] origArgs = args;
254 for (int i = 0; i < args.length; i++) {
255 Object arg = args[i];
256 Object x = Context.jsToJava(arg, argTypes[i]);
257 if (x != arg) {
258 if (args == origArgs) {
259 args = origArgs.clone();
260 }
261 args[i] = x;
262 }
263 }
264 }
265
266 return ctor.newInstance(args);
267 }
268
269 @Override
270 public String toString() {
271 return "[JavaClass " + getClassObject().getName() + "]";
272 }
273
274 /**
275 * Determines if prototype is a wrapped Java object and performs
276 * a Java "instanceof".
277 * Exception: if value is an instance of NativeJavaClass, it isn't
278 * considered an instance of the Java class; this forestalls any
279 * name conflicts between java.lang.Class's methods and the
280 * static methods exposed by a JavaNativeClass.
281 */
282 @Override
283 public boolean hasInstance(Scriptable value) {
284
285 if (value instanceof Wrapper &&
286 !(value instanceof NativeJavaClass)) {
287 Object instance = ((Wrapper)value).unwrap();
288
289 return getClassObject().isInstance(instance);
290 }
291
292 // value wasn't something we understand
293 return false;
294 }
295
296 private static Class<?> findNestedClass(Class<?> parentClass, String name) {
297 String nestedClassName = parentClass.getName() + '$' + name;
298 ClassLoader loader = parentClass.getClassLoader();
299 if (loader == null) {
300 // ALERT: if loader is null, nested class should be loaded
301 // via system class loader which can be different from the
302 // loader that brought Rhino classes that Class.forName() would
303 // use, but ClassLoader.getSystemClassLoader() is Java 2 only
304 return Kit.classOrNull(nestedClassName);
305 } else {
306 return Kit.classOrNull(loader, nestedClassName);
307 }
308 }
309
310 private Map<String,FieldAndMethods> staticFieldAndMethods;
311 }