Debian Codegraph @

rhino/src/org/mozilla/javascript/JavaMembers.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.*;
11
12 import static java.lang.reflect.Modifier.isProtected;
13 import static java.lang.reflect.Modifier.isPublic;
14
15 /**
16 *
17 * @author Mike Shaver
18 * @author Norris Boyd
19 * @see NativeJavaObject
20 * @see NativeJavaClass
21 */
22 class JavaMembers
23 {
24 JavaMembers(Scriptable scope, Class<?> cl)
25 {
26 this(scope, cl, false);
27 }
28
29 JavaMembers(Scriptable scope, Class<?> cl, boolean includeProtected)
30 {
31 try {
32 Context cx = ContextFactory.getGlobal().enterContext();
33 ClassShutter shutter = cx.getClassShutter();
34 if (shutter != null && !shutter.visibleToScripts(cl.getName())) {
35 throw Context.reportRuntimeError1("msg.access.prohibited",
36 cl.getName());
37 }
38 this.members = new HashMap<String,Object>();
39 this.staticMembers = new HashMap<String,Object>();
40 this.cl = cl;
41 boolean includePrivate = cx.hasFeature(
42 Context.FEATURE_ENHANCED_JAVA_ACCESS);
43 reflect(scope, includeProtected, includePrivate);
44 } finally {
45 Context.exit();
46 }
47 }
48
49 boolean has(String name, boolean isStatic)
50 {
51 Map<String,Object> ht = isStatic ? staticMembers : members;
52 Object obj = ht.get(name);
53 if (obj != null) {
54 return true;
55 }
56 return findExplicitFunction(name, isStatic) != null;
57 }
58
59 Object get(Scriptable scope, String name, Object javaObject,
60 boolean isStatic)
61 {
62 Map<String,Object> ht = isStatic ? staticMembers : members;
63 Object member = ht.get(name);
64 if (!isStatic && member == null) {
65 // Try to get static member from instance (LC3)
66 member = staticMembers.get(name);
67 }
68 if (member == null) {
69 member = this.getExplicitFunction(scope, name,
70 javaObject, isStatic);
71 if (member == null)
72 return Scriptable.NOT_FOUND;
73 }
74 if (member instanceof Scriptable) {
75 return member;
76 }
77 Context cx = Context.getContext();
78 Object rval;
79 Class<?> type;
80 try {
81 if (member instanceof BeanProperty) {
82 BeanProperty bp = (BeanProperty) member;
83 if (bp.getter == null)
84 return Scriptable.NOT_FOUND;
85 rval = bp.getter.invoke(javaObject, Context.emptyArgs);
86 type = bp.getter.method().getReturnType();
87 } else {
88 Field field = (Field) member;
89 rval = field.get(isStatic ? null : javaObject);
90 type = field.getType();
91 }
92 } catch (Exception ex) {
93 throw Context.throwAsScriptRuntimeEx(ex);
94 }
95 // Need to wrap the object before we return it.
96 scope = ScriptableObject.getTopLevelScope(scope);
97 return cx.getWrapFactory().wrap(cx, scope, rval, type);
98 }
99
100 void put(Scriptable scope, String name, Object javaObject,
101 Object value, boolean isStatic)
102 {
103 Map<String,Object> ht = isStatic ? staticMembers : members;
104 Object member = ht.get(name);
105 if (!isStatic && member == null) {
106 // Try to get static member from instance (LC3)
107 member = staticMembers.get(name);
108 }
109 if (member == null)
110 throw reportMemberNotFound(name);
111 if (member instanceof FieldAndMethods) {
112 FieldAndMethods fam = (FieldAndMethods) ht.get(name);
113 member = fam.field;
114 }
115
116 // Is this a bean property "set"?
117 if (member instanceof BeanProperty) {
118 BeanProperty bp = (BeanProperty)member;
119 if (bp.setter == null) {
120 throw reportMemberNotFound(name);
121 }
122 // If there's only one setter or if the value is null, use the
123 // main setter. Otherwise, let the NativeJavaMethod decide which
124 // setter to use:
125 if (bp.setters == null || value == null) {
126 Class<?> setType = bp.setter.argTypes[0];
127 Object[] args = { Context.jsToJava(value, setType) };
128 try {
129 bp.setter.invoke(javaObject, args);
130 } catch (Exception ex) {
131 throw Context.throwAsScriptRuntimeEx(ex);
132 }
133 } else {
134 Object[] args = { value };
135 bp.setters.call(Context.getContext(),
136 ScriptableObject.getTopLevelScope(scope),
137 scope, args);
138 }
139 }
140 else {
141 if (!(member instanceof Field)) {
142 String str = (member == null) ? "msg.java.internal.private"
143 : "msg.java.method.assign";
144 throw Context.reportRuntimeError1(str, name);
145 }
146 Field field = (Field)member;
147 Object javaValue = Context.jsToJava(value, field.getType());
148 try {
149 field.set(javaObject, javaValue);
150 } catch (IllegalAccessException accessEx) {
151 if ((field.getModifiers() & Modifier.FINAL) != 0) {
152 // treat Java final the same as JavaScript [[READONLY]]
153 return;
154 }
155 throw Context.throwAsScriptRuntimeEx(accessEx);
156 } catch (IllegalArgumentException argEx) {
157 throw Context.reportRuntimeError3(
158 "msg.java.internal.field.type",
159 value.getClass().getName(), field,
160 javaObject.getClass().getName());
161 }
162 }
163 }
164
165 Object[] getIds(boolean isStatic)
166 {
167 Map<String,Object> map = isStatic ? staticMembers : members;
168 return map.keySet().toArray(new Object[map.size()]);
169 }
170
171 static String javaSignature(Class<?> type)
172 {
173 if (!type.isArray()) {
174 return type.getName();
175 } else {
176 int arrayDimension = 0;
177 do {
178 ++arrayDimension;
179 type = type.getComponentType();
180 } while (type.isArray());
181 String name = type.getName();
182 String suffix = "[]";
183 if (arrayDimension == 1) {
184 return name.concat(suffix);
185 } else {
186 int length = name.length() + arrayDimension * suffix.length();
187 StringBuilder sb = new StringBuilder(length);
188 sb.append(name);
189 while (arrayDimension != 0) {
190 --arrayDimension;
191 sb.append(suffix);
192 }
193 return sb.toString();
194 }
195 }
196 }
197
198 static String liveConnectSignature(Class<?>[] argTypes)
199 {
200 int N = argTypes.length;
201 if (N == 0) { return "()"; }
202 StringBuilder sb = new StringBuilder();
203 sb.append('(');
204 for (int i = 0; i != N; ++i) {
205 if (i != 0) {
206 sb.append(',');
207 }
208 sb.append(javaSignature(argTypes[i]));
209 }
210 sb.append(')');
211 return sb.toString();
212 }
213
214 private MemberBox findExplicitFunction(String name, boolean isStatic)
215 {
216 int sigStart = name.indexOf('(');
217 if (sigStart < 0) { return null; }
218
219 Map<String,Object> ht = isStatic ? staticMembers : members;
220 MemberBox[] methodsOrCtors = null;
221 boolean isCtor = (isStatic && sigStart == 0);
222
223 if (isCtor) {
224 // Explicit request for an overloaded constructor
225 methodsOrCtors = ctors.methods;
226 } else {
227 // Explicit request for an overloaded method
228 String trueName = name.substring(0,sigStart);
229 Object obj = ht.get(trueName);
230 if (!isStatic && obj == null) {
231 // Try to get static member from instance (LC3)
232 obj = staticMembers.get(trueName);
233 }
234 if (obj instanceof NativeJavaMethod) {
235 NativeJavaMethod njm = (NativeJavaMethod)obj;
236 methodsOrCtors = njm.methods;
237 }
238 }
239
240 if (methodsOrCtors != null) {
241 for (MemberBox methodsOrCtor : methodsOrCtors) {
242 Class<?>[] type = methodsOrCtor.argTypes;
243 String sig = liveConnectSignature(type);
244 if (sigStart + sig.length() == name.length()
245 && name.regionMatches(sigStart, sig, 0, sig.length()))
246 {
247 return methodsOrCtor;
248 }
249 }
250 }
251
252 return null;
253 }
254
255 private Object getExplicitFunction(Scriptable scope, String name,
256 Object javaObject, boolean isStatic)
257 {
258 Map<String,Object> ht = isStatic ? staticMembers : members;
259 Object member = null;
260 MemberBox methodOrCtor = findExplicitFunction(name, isStatic);
261
262 if (methodOrCtor != null) {
263 Scriptable prototype =
264 ScriptableObject.getFunctionPrototype(scope);
265
266 if (methodOrCtor.isCtor()) {
267 NativeJavaConstructor fun =
268 new NativeJavaConstructor(methodOrCtor);
269 fun.setPrototype(prototype);
270 member = fun;
271 ht.put(name, fun);
272 } else {
273 String trueName = methodOrCtor.getName();
274 member = ht.get(trueName);
275
276 if (member instanceof NativeJavaMethod &&
277 ((NativeJavaMethod)member).methods.length > 1 ) {
278 NativeJavaMethod fun =
279 new NativeJavaMethod(methodOrCtor, name);
280 fun.setPrototype(prototype);
281 ht.put(name, fun);
282 member = fun;
283 }
284 }
285 }
286
287 return member;
288 }
289
290 /**
291 * Retrieves mapping of methods to accessible methods for a class.
292 * In case the class is not public, retrieves methods with same
293 * signature as its public methods from public superclasses and
294 * interfaces (if they exist). Basically upcasts every method to the
295 * nearest accessible method.
296 */
297 private static Method[] discoverAccessibleMethods(Class<?> clazz,
298 boolean includeProtected,
299 boolean includePrivate)
300 {
301 Map<MethodSignature,Method> map = new HashMap<MethodSignature,Method>();
302 discoverAccessibleMethods(clazz, map, includeProtected, includePrivate);
303 return map.values().toArray(new Method[map.size()]);
304 }
305
306 private static void discoverAccessibleMethods(Class<?> clazz,
307 Map<MethodSignature,Method> map, boolean includeProtected,
308 boolean includePrivate)
309 {
310 if (isPublic(clazz.getModifiers()) || includePrivate) {
311 try {
312 if (includeProtected || includePrivate) {
313 while (clazz != null) {
314 try {
315 Method[] methods = clazz.getDeclaredMethods();
316 for (Method method : methods) {
317 int mods = method.getModifiers();
318
319 if (isPublic(mods)
320 || isProtected(mods)
321 || includePrivate) {
322 MethodSignature sig = new MethodSignature(method);
323 if (!map.containsKey(sig)) {
324 if (includePrivate && !method.isAccessible())
325 method.setAccessible(true);
326 map.put(sig, method);
327 }
328 }
329 }
330 clazz = clazz.getSuperclass();
331 } catch (SecurityException e) {
332 // Some security settings (i.e., applets) disallow
333 // access to Class.getDeclaredMethods. Fall back to
334 // Class.getMethods.
335 Method[] methods = clazz.getMethods();
336 for (Method method : methods) {
337 MethodSignature sig = new MethodSignature(method);
338 if (!map.containsKey(sig))
339 map.put(sig, method);
340 }
341 break; // getMethods gets superclass methods, no
342 // need to loop any more
343 }
344 }
345 } else {
346 Method[] methods = clazz.getMethods();
347 for (Method method : methods) {
348 MethodSignature sig = new MethodSignature(method);
349 // Array may contain methods with same signature but different return value!
350 if (!map.containsKey(sig))
351 map.put(sig, method);
352 }
353 }
354 return;
355 } catch (SecurityException e) {
356 Context.reportWarning(
357 "Could not discover accessible methods of class " +
358 clazz.getName() + " due to lack of privileges, " +
359 "attemping superclasses/interfaces.");
360 // Fall through and attempt to discover superclass/interface
361 // methods
362 }
363 }
364
365 Class<?>[] interfaces = clazz.getInterfaces();
366 for (Class<?> intface : interfaces) {
367 discoverAccessibleMethods(intface, map, includeProtected,
368 includePrivate);
369 }
370 Class<?> superclass = clazz.getSuperclass();
371 if (superclass != null) {
372 discoverAccessibleMethods(superclass, map, includeProtected,
373 includePrivate);
374 }
375 }
376
377 private static final class MethodSignature
378 {
379 private final String name;
380 private final Class<?>[] args;
381
382 private MethodSignature(String name, Class<?>[] args)
383 {
384 this.name = name;
385 this.args = args;
386 }
387
388 MethodSignature(Method method)
389 {
390 this(method.getName(), method.getParameterTypes());
391 }
392
393 @Override
394 public boolean equals(Object o)
395 {
396 if(o instanceof MethodSignature)
397 {
398 MethodSignature ms = (MethodSignature)o;
399 return ms.name.equals(name) && Arrays.equals(args, ms.args);
400 }
401 return false;
402 }
403
404 @Override
405 public int hashCode()
406 {
407 return name.hashCode() ^ args.length;
408 }
409 }
410
411 private void reflect(Scriptable scope,
412 boolean includeProtected,
413 boolean includePrivate)
414 {
415 // We reflect methods first, because we want overloaded field/method
416 // names to be allocated to the NativeJavaMethod before the field
417 // gets in the way.
418
419 Method[] methods = discoverAccessibleMethods(cl, includeProtected,
420 includePrivate);
421 for (Method method : methods) {
422 int mods = method.getModifiers();
423 boolean isStatic = Modifier.isStatic(mods);
424 Map<String,Object> ht = isStatic ? staticMembers : members;
425 String name = method.getName();
426 Object value = ht.get(name);
427 if (value == null) {
428 ht.put(name, method);
429 } else {
430 ObjArray overloadedMethods;
431 if (value instanceof ObjArray) {
432 overloadedMethods = (ObjArray)value;
433 } else {
434 if (!(value instanceof Method)) Kit.codeBug();
435 // value should be instance of Method as at this stage
436 // staticMembers and members can only contain methods
437 overloadedMethods = new ObjArray();
438 overloadedMethods.add(value);
439 ht.put(name, overloadedMethods);
440 }
441 overloadedMethods.add(method);
442 }
443 }
444
445 // replace Method instances by wrapped NativeJavaMethod objects
446 // first in staticMembers and then in members
447 for (int tableCursor = 0; tableCursor != 2; ++tableCursor) {
448 boolean isStatic = (tableCursor == 0);
449 Map<String,Object> ht = isStatic ? staticMembers : members;
450 for (Map.Entry<String, Object> entry: ht.entrySet()) {
451 MemberBox[] methodBoxes;
452 Object value = entry.getValue();
453 if (value instanceof Method) {
454 methodBoxes = new MemberBox[1];
455 methodBoxes[0] = new MemberBox((Method)value);
456 } else {
457 ObjArray overloadedMethods = (ObjArray)value;
458 int N = overloadedMethods.size();
459 if (N < 2) Kit.codeBug();
460 methodBoxes = new MemberBox[N];
461 for (int i = 0; i != N; ++i) {
462 Method method = (Method)overloadedMethods.get(i);
463 methodBoxes[i] = new MemberBox(method);
464 }
465 }
466 NativeJavaMethod fun = new NativeJavaMethod(methodBoxes);
467 if (scope != null) {
468 ScriptRuntime.setFunctionProtoAndParent(fun, scope);
469 }
470 ht.put(entry.getKey(), fun);
471 }
472 }
473
474 // Reflect fields.
475 Field[] fields = getAccessibleFields(includeProtected, includePrivate);
476 for (Field field : fields) {
477 String name = field.getName();
478 int mods = field.getModifiers();
479 try {
480 boolean isStatic = Modifier.isStatic(mods);
481 Map<String,Object> ht = isStatic ? staticMembers : members;
482 Object member = ht.get(name);
483 if (member == null) {
484 ht.put(name, field);
485 } else if (member instanceof NativeJavaMethod) {
486 NativeJavaMethod method = (NativeJavaMethod) member;
487 FieldAndMethods fam
488 = new FieldAndMethods(scope, method.methods, field);
489 Map<String,FieldAndMethods> fmht = isStatic ? staticFieldAndMethods
490 : fieldAndMethods;
491 if (fmht == null) {
492 fmht = new HashMap<String,FieldAndMethods>();
493 if (isStatic) {
494 staticFieldAndMethods = fmht;
495 } else {
496 fieldAndMethods = fmht;
497 }
498 }
499 fmht.put(name, fam);
500 ht.put(name, fam);
501 } else if (member instanceof Field) {
502 Field oldField = (Field) member;
503 // If this newly reflected field shadows an inherited field,
504 // then replace it. Otherwise, since access to the field
505 // would be ambiguous from Java, no field should be
506 // reflected.
507 // For now, the first field found wins, unless another field
508 // explicitly shadows it.
509 if (oldField.getDeclaringClass().
510 isAssignableFrom(field.getDeclaringClass()))
511 {
512 ht.put(name, field);
513 }
514 } else {
515 // "unknown member type"
516 Kit.codeBug();
517 }
518 } catch (SecurityException e) {
519 // skip this field
520 Context.reportWarning("Could not access field "
521 + name + " of class " + cl.getName() +
522 " due to lack of privileges.");
523 }
524 }
525
526 // Create bean properties from corresponding get/set methods first for
527 // static members and then for instance members
528 for (int tableCursor = 0; tableCursor != 2; ++tableCursor) {
529 boolean isStatic = (tableCursor == 0);
530 Map<String,Object> ht = isStatic ? staticMembers : members;
531
532 Map<String,BeanProperty> toAdd = new HashMap<String,BeanProperty>();
533
534 // Now, For each member, make "bean" properties.
535 for (String name: ht.keySet()) {
536 // Is this a getter?
537 boolean memberIsGetMethod = name.startsWith("get");
538 boolean memberIsSetMethod = name.startsWith("set");
539 boolean memberIsIsMethod = name.startsWith("is");
540 if (memberIsGetMethod || memberIsIsMethod
541 || memberIsSetMethod) {
542 // Double check name component.
543 String nameComponent
544 = name.substring(memberIsIsMethod ? 2 : 3);
545 if (nameComponent.length() == 0)
546 continue;
547
548 // Make the bean property name.
549 String beanPropertyName = nameComponent;
550 char ch0 = nameComponent.charAt(0);
551 if (Character.isUpperCase(ch0)) {
552 if (nameComponent.length() == 1) {
553 beanPropertyName = nameComponent.toLowerCase();
554 } else {
555 char ch1 = nameComponent.charAt(1);
556 if (!Character.isUpperCase(ch1)) {
557 beanPropertyName = Character.toLowerCase(ch0)
558 +nameComponent.substring(1);
559 }
560 }
561 }
562
563 // If we already have a member by this name, don't do this
564 // property.
565 if (toAdd.containsKey(beanPropertyName))
566 continue;
567 Object v = ht.get(beanPropertyName);
568 if (v != null) {
569 // A private field shouldn't mask a public getter/setter
570 if (!includePrivate || !(v instanceof Member) ||
571 !Modifier.isPrivate(((Member)v).getModifiers()))
572
573 {
574 continue;
575 }
576 }
577
578 // Find the getter method, or if there is none, the is-
579 // method.
580 MemberBox getter = null;
581 getter = findGetter(isStatic, ht, "get", nameComponent);
582 // If there was no valid getter, check for an is- method.
583 if (getter == null) {
584 getter = findGetter(isStatic, ht, "is", nameComponent);
585 }
586
587 // setter
588 MemberBox setter = null;
589 NativeJavaMethod setters = null;
590 String setterName = "set".concat(nameComponent);
591
592 if (ht.containsKey(setterName)) {
593 // Is this value a method?
594 Object member = ht.get(setterName);
595 if (member instanceof NativeJavaMethod) {
596 NativeJavaMethod njmSet = (NativeJavaMethod)member;
597 if (getter != null) {
598 // We have a getter. Now, do we have a matching
599 // setter?
600 Class<?> type = getter.method().getReturnType();
601 setter = extractSetMethod(type, njmSet.methods,
602 isStatic);
603 } else {
604 // No getter, find any set method
605 setter = extractSetMethod(njmSet.methods,
606 isStatic);
607 }
608 if (njmSet.methods.length > 1) {
609 setters = njmSet;
610 }
611 }
612 }
613 // Make the property.
614 BeanProperty bp = new BeanProperty(getter, setter,
615 setters);
616 toAdd.put(beanPropertyName, bp);
617 }
618 }
619
620 // Add the new bean properties.
621 for (String key: toAdd.keySet()) {
622 Object value = toAdd.get(key);
623 ht.put(key, value);
624 }
625 }
626
627 // Reflect constructors
628 Constructor<?>[] constructors = getAccessibleConstructors(includePrivate);
629 MemberBox[] ctorMembers = new MemberBox[constructors.length];
630 for (int i = 0; i != constructors.length; ++i) {
631 ctorMembers[i] = new MemberBox(constructors[i]);
632 }
633 ctors = new NativeJavaMethod(ctorMembers, cl.getSimpleName());
634 }
635
636 private Constructor<?>[] getAccessibleConstructors(boolean includePrivate)
637 {
638 // The JVM currently doesn't allow changing access on java.lang.Class
639 // constructors, so don't try
640 if (includePrivate && cl != ScriptRuntime.ClassClass) {
641 try {
642 Constructor<?>[] cons = cl.getDeclaredConstructors();
643 AccessibleObject.setAccessible(cons, true);
644
645 return cons;
646 } catch (SecurityException e) {
647 // Fall through to !includePrivate case
648 Context.reportWarning("Could not access constructor " +
649 " of class " + cl.getName() +
650 " due to lack of privileges.");
651 }
652 }
653 return cl.getConstructors();
654 }
655
656 private Field[] getAccessibleFields(boolean includeProtected,
657 boolean includePrivate) {
658 if (includePrivate || includeProtected) {
659 try {
660 List<Field> fieldsList = new ArrayList<Field>();
661 Class<?> currentClass = cl;
662
663 while (currentClass != null) {
664 // get all declared fields in this class, make them
665 // accessible, and save
666 Field[] declared = currentClass.getDeclaredFields();
667 for (Field field : declared) {
668 int mod = field.getModifiers();
669 if (includePrivate || isPublic(mod) || isProtected(mod)) {
670 if (!field.isAccessible())
671 field.setAccessible(true);
672 fieldsList.add(field);
673 }
674 }
675 // walk up superclass chain. no need to deal specially with
676 // interfaces, since they can't have fields
677 currentClass = currentClass.getSuperclass();
678 }
679
680 return fieldsList.toArray(new Field[fieldsList.size()]);
681 } catch (SecurityException e) {
682 // fall through to !includePrivate case
683 }
684 }
685 return cl.getFields();
686 }
687
688 private MemberBox findGetter(boolean isStatic, Map<String,Object> ht, String prefix,
689 String propertyName)
690 {
691 String getterName = prefix.concat(propertyName);
692 if (ht.containsKey(getterName)) {
693 // Check that the getter is a method.
694 Object member = ht.get(getterName);
695 if (member instanceof NativeJavaMethod) {
696 NativeJavaMethod njmGet = (NativeJavaMethod) member;
697 return extractGetMethod(njmGet.methods, isStatic);
698 }
699 }
700 return null;
701 }
702
703 private static MemberBox extractGetMethod(MemberBox[] methods,
704 boolean isStatic)
705 {
706 // Inspect the list of all MemberBox for the only one having no
707 // parameters
708 for (MemberBox method : methods) {
709 // Does getter method have an empty parameter list with a return
710 // value (eg. a getSomething() or isSomething())?
711 if (method.argTypes.length == 0 && (!isStatic || method.isStatic())) {
712 Class<?> type = method.method().getReturnType();
713 if (type != Void.TYPE) {
714 return method;
715 }
716 break;
717 }
718 }
719 return null;
720 }
721
722 private static MemberBox extractSetMethod(Class<?> type, MemberBox[] methods,
723 boolean isStatic)
724 {
725 //
726 // Note: it may be preferable to allow NativeJavaMethod.findFunction()
727 // to find the appropriate setter; unfortunately, it requires an
728 // instance of the target arg to determine that.
729 //
730
731 // Make two passes: one to find a method with direct type assignment,
732 // and one to find a widening conversion.
733 for (int pass = 1; pass <= 2; ++pass) {
734 for (MemberBox method : methods) {
735 if (!isStatic || method.isStatic()) {
736 Class<?>[] params = method.argTypes;
737 if (params.length == 1) {
738 if (pass == 1) {
739 if (params[0] == type) {
740 return method;
741 }
742 } else {
743 if (pass != 2) Kit.codeBug();
744 if (params[0].isAssignableFrom(type)) {
745 return method;
746 }
747 }
748 }
749 }
750 }
751 }
752 return null;
753 }
754
755 private static MemberBox extractSetMethod(MemberBox[] methods,
756 boolean isStatic)
757 {
758
759 for (MemberBox method : methods) {
760 if (!isStatic || method.isStatic()) {
761 if (method.method().getReturnType() == Void.TYPE) {
762 if (method.argTypes.length == 1) {
763 return method;
764 }
765 }
766 }
767 }
768 return null;
769 }
770
771 Map<String,FieldAndMethods> getFieldAndMethodsObjects(Scriptable scope,
772 Object javaObject, boolean isStatic)
773 {
774 Map<String,FieldAndMethods> ht = isStatic ? staticFieldAndMethods : fieldAndMethods;
775 if (ht == null)
776 return null;
777 int len = ht.size();
778 Map<String,FieldAndMethods> result = new HashMap<String,FieldAndMethods>(len);
779 for (FieldAndMethods fam: ht.values()) {
780 FieldAndMethods famNew = new FieldAndMethods(scope, fam.methods,
781 fam.field);
782 famNew.javaObject = javaObject;
783 result.put(fam.field.getName(), famNew);
784 }
785 return result;
786 }
787
788 static JavaMembers lookupClass(Scriptable scope, Class<?> dynamicType,
789 Class<?> staticType, boolean includeProtected)
790 {
791 JavaMembers members;
792 ClassCache cache = ClassCache.get(scope);
793 Map<Class<?>,JavaMembers> ct = cache.getClassCacheMap();
794
795 Class<?> cl = dynamicType;
796 for (;;) {
797 members = ct.get(cl);
798 if (members != null) {
799 if (cl != dynamicType) {
800 // member lookup for the original class failed because of
801 // missing privileges, cache the result so we don't try again
802 ct.put(dynamicType, members);
803 }
804 return members;
805 }
806 try {
807 members = new JavaMembers(cache.getAssociatedScope(), cl,
808 includeProtected);
809 break;
810 } catch (SecurityException e) {
811 // Reflection may fail for objects that are in a restricted
812 // access package (e.g. sun.*). If we get a security
813 // exception, try again with the static type if it is interface.
814 // Otherwise, try superclass
815 if (staticType != null && staticType.isInterface()) {
816 cl = staticType;
817 staticType = null; // try staticType only once
818 } else {
819 Class<?> parent = cl.getSuperclass();
820 if (parent == null) {
821 if (cl.isInterface()) {
822 // last resort after failed staticType interface
823 parent = ScriptRuntime.ObjectClass;
824 } else {
825 throw e;
826 }
827 }
828 cl = parent;
829 }
830 }
831 }
832
833 if (cache.isCachingEnabled()) {
834 ct.put(cl, members);
835 if (cl != dynamicType) {
836 // member lookup for the original class failed because of
837 // missing privileges, cache the result so we don't try again
838 ct.put(dynamicType, members);
839 }
840 }
841 return members;
842 }
843
844 RuntimeException reportMemberNotFound(String memberName)
845 {
846 return Context.reportRuntimeError2(
847 "msg.java.member.not.found", cl.getName(), memberName);
848 }
849
850 private Class<?> cl;
851 private Map<String,Object> members;
852 private Map<String,FieldAndMethods> fieldAndMethods;
853 private Map<String,Object> staticMembers;
854 private Map<String,FieldAndMethods> staticFieldAndMethods;
855 NativeJavaMethod ctors; // we use NativeJavaMethod for ctor overload resolution
856 }
857
858 class BeanProperty
859 {
860 BeanProperty(MemberBox getter, MemberBox setter, NativeJavaMethod setters)
861 {
862 this.getter = getter;
863 this.setter = setter;
864 this.setters = setters;
865 }
866
867 MemberBox getter;
868 MemberBox setter;
869 NativeJavaMethod setters;
870 }
871
872 class FieldAndMethods extends NativeJavaMethod
873 {
874 static final long serialVersionUID = -9222428244284796755L;
875
876 FieldAndMethods(Scriptable scope, MemberBox[] methods, Field field)
877 {
878 super(methods);
879 this.field = field;
880 setParentScope(scope);
881 setPrototype(ScriptableObject.getFunctionPrototype(scope));
882 }
883
884 @Override
885 public Object getDefaultValue(Class<?> hint)
886 {
887 if (hint == ScriptRuntime.FunctionClass)
888 return this;
889 Object rval;
890 Class<?> type;
891 try {
892 rval = field.get(javaObject);
893 type = field.getType();
894 } catch (IllegalAccessException accEx) {
895 throw Context.reportRuntimeError1(
896 "msg.java.internal.private", field.getName());
897 }
898 Context cx = Context.getContext();
899 rval = cx.getWrapFactory().wrap(cx, this, rval, type);
900 if (rval instanceof Scriptable) {
901 rval = ((Scriptable) rval).getDefaultValue(hint);
902 }
903 return rval;
904 }
905
906 Field field;
907 Object javaObject;
908 }