01: /*
02: * @(#)javaAdapter.java 1.2 04/12/06
03: *
04: * Copyright (c) 1997-2004 Sun Microsystems, Inc. All Rights Reserved.
05: *
06: * See the file "LICENSE.txt" for information on usage and redistribution
07: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
08: */
09: package org.pnuts.lib;
10:
11: import pnuts.lang.Context;
12: import pnuts.lang.PnutsFunction;
13: import pnuts.lang.PnutsException;
14: import pnuts.lang.Package;
15: import pnuts.lang.Runtime;
16: import java.util.Enumeration;
17: import java.util.Map;
18: import java.util.ArrayList;
19: import java.util.Collection;
20: import org.pnuts.lang.SubtypeGenerator;
21:
22: public class javaAdapter extends PnutsFunction {
23:
24: public javaAdapter() {
25: super ("javaAdapter");
26: }
27:
28: public boolean defined(int nargs) {
29: return nargs >= 2;
30: }
31:
32: protected Object exec(Object[] args, Context context) {
33: if (args.length < 2) {
34: undefined(args, context);
35: return null;
36: }
37: Object super types = args[0];
38: Class super class = null;
39: ArrayList interfaces = null;
40: Class c;
41: if (Runtime.isArray(super types)
42: || (super types instanceof Collection)) {
43: interfaces = new ArrayList();
44: Enumeration e = Runtime.toEnumeration(super types, context);
45: while (e.hasMoreElements()) {
46: c = (Class) e.nextElement();
47: if (c.isInterface()) {
48: interfaces.add(c);
49: } else {
50: if (super class != null) {
51: throw new IllegalArgumentException(
52: "multiple inheritance: "
53: + super class.getName() + ","
54: + c.getName());
55: }
56: super class = c;
57: }
58: }
59: } else {
60: c = (Class) super types;
61: if (c.isInterface()) {
62: interfaces = new ArrayList();
63: interfaces.add(c);
64: } else {
65: super class = c;
66: }
67: }
68: Object arg1 = args[1];
69: Package pkg = null;
70: if (arg1 instanceof Map) {
71: pkg = new MapPackage((Map) arg1);
72: } else if (arg1 instanceof Package) {
73: pkg = (Package) arg1;
74: } else {
75: throw new IllegalArgumentException(String.valueOf(arg1));
76: }
77: Object[] a;
78: if (args.length > 2) {
79: a = new Object[args.length - 2];
80: System.arraycopy(args, 2, a, 0, args.length - 2);
81: } else {
82: a = new Object[] {};
83: }
84: Class[] array = null;
85: if (interfaces != null) {
86: array = new Class[interfaces.size()];
87: interfaces.toArray(array);
88: }
89: return SubtypeGenerator.instantiateSubtype(context, super class,
90: array, pkg, a);
91: }
92:
93: public String toString() {
94: return "function javaAdapter((supertype|supertypes[]), pkgOrMap, args...)";
95: }
96: }
|