Source Code Cross Referenced for BSHAllocationExpression.java in  » Scripting » beanshell » bsh » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Scripting » beanshell » bsh 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*****************************************************************************
002:         *                                                                           *
003:         *  This file is part of the BeanShell Java Scripting distribution.          *
004:         *  Documentation and updates may be found at http://www.beanshell.org/      *
005:         *                                                                           *
006:         *  Sun Public License Notice:                                               *
007:         *                                                                           *
008:         *  The contents of this file are subject to the Sun Public License Version  *
009:         *  1.0 (the "License"); you may not use this file except in compliance with *
010:         *  the License. A copy of the License is available at http://www.sun.com    * 
011:         *                                                                           *
012:         *  The Original Code is BeanShell. The Initial Developer of the Original    *
013:         *  Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright     *
014:         *  (C) 2000.  All Rights Reserved.                                          *
015:         *                                                                           *
016:         *  GNU Public License Notice:                                               *
017:         *                                                                           *
018:         *  Alternatively, the contents of this file may be used under the terms of  *
019:         *  the GNU Lesser General Public License (the "LGPL"), in which case the    *
020:         *  provisions of LGPL are applicable instead of those above. If you wish to *
021:         *  allow use of your version of this file only under the  terms of the LGPL *
022:         *  and not to allow others to use your version of this file under the SPL,  *
023:         *  indicate your decision by deleting the provisions above and replace      *
024:         *  them with the notice and other provisions required by the LGPL.  If you  *
025:         *  do not delete the provisions above, a recipient may use your version of  *
026:         *  this file under either the SPL or the LGPL.                              *
027:         *                                                                           *
028:         *  Patrick Niemeyer (pat@pat.net)                                           *
029:         *  Author of Learning Java, O'Reilly & Associates                           *
030:         *  http://www.pat.net/~pat/                                                 *
031:         *                                                                           *
032:         *****************************************************************************/package bsh;
033:
034:        import java.lang.reflect.Array;
035:        import java.lang.reflect.InvocationTargetException;
036:
037:        /**
038:         New object, new array, or inner class style allocation with body.
039:         */
040:        class BSHAllocationExpression extends SimpleNode {
041:            BSHAllocationExpression(int id) {
042:                super (id);
043:            }
044:
045:            private static int innerClassCount = 0;
046:
047:            public Object eval(CallStack callstack, Interpreter interpreter)
048:                    throws EvalError {
049:                // type is either a class name or a primitive type
050:                SimpleNode type = (SimpleNode) jjtGetChild(0);
051:
052:                // args is either constructor arguments or array dimensions
053:                SimpleNode args = (SimpleNode) jjtGetChild(1);
054:
055:                if (type instanceof  BSHAmbiguousName) {
056:                    BSHAmbiguousName name = (BSHAmbiguousName) type;
057:
058:                    if (args instanceof  BSHArguments)
059:                        return objectAllocation(name, (BSHArguments) args,
060:                                callstack, interpreter);
061:                    else
062:                        return objectArrayAllocation(name,
063:                                (BSHArrayDimensions) args, callstack,
064:                                interpreter);
065:                } else
066:                    return primitiveArrayAllocation((BSHPrimitiveType) type,
067:                            (BSHArrayDimensions) args, callstack, interpreter);
068:            }
069:
070:            private Object objectAllocation(BSHAmbiguousName nameNode,
071:                    BSHArguments argumentsNode, CallStack callstack,
072:                    Interpreter interpreter) throws EvalError {
073:                NameSpace namespace = callstack.top();
074:
075:                Object[] args = argumentsNode.getArguments(callstack,
076:                        interpreter);
077:                if (args == null)
078:                    throw new EvalError("Null args in new.", this , callstack);
079:
080:                // Look for scripted class object
081:                Object obj = nameNode
082:                        .toObject(callstack, interpreter, false/* force class*/);
083:
084:                // Try regular class
085:
086:                obj = nameNode
087:                        .toObject(callstack, interpreter, true/*force class*/);
088:
089:                Class type = null;
090:                if (obj instanceof  ClassIdentifier)
091:                    type = ((ClassIdentifier) obj).getTargetClass();
092:                else
093:                    throw new EvalError("Unknown class: " + nameNode.text,
094:                            this , callstack);
095:
096:                // Is an inner class style object allocation
097:                boolean hasBody = jjtGetNumChildren() > 2;
098:
099:                if (hasBody) {
100:                    BSHBlock body = (BSHBlock) jjtGetChild(2);
101:                    if (type.isInterface())
102:                        return constructWithInterfaceBody(type, args, body,
103:                                callstack, interpreter);
104:                    else
105:                        return constructWithClassBody(type, args, body,
106:                                callstack, interpreter);
107:                } else
108:                    return constructObject(type, args, callstack);
109:            }
110:
111:            private Object constructObject(Class type, Object[] args,
112:                    CallStack callstack) throws EvalError {
113:                Object obj;
114:                try {
115:                    obj = Reflect.constructObject(type, args);
116:                } catch (ReflectError e) {
117:                    throw new EvalError("Constructor error: " + e.getMessage(),
118:                            this , callstack);
119:                } catch (InvocationTargetException e) {
120:                    // No need to wrap this debug
121:                    Interpreter.debug("The constructor threw an exception:\n\t"
122:                            + e.getTargetException());
123:                    throw new TargetError("Object constructor", e
124:                            .getTargetException(), this , callstack, true);
125:                }
126:
127:                String className = type.getName();
128:                // Is it an inner class?
129:                if (className.indexOf("$") == -1)
130:                    return obj;
131:
132:                // Temporary hack to support inner classes 
133:                // If the obj is a non-static inner class then import the context...
134:                // This is not a sufficient emulation of inner classes.
135:                // Replace this later...
136:
137:                // work through to class 'this'
138:                This ths = callstack.top().getThis(null);
139:                NameSpace instanceNameSpace = Name.getClassNameSpace(ths
140:                        .getNameSpace());
141:
142:                // Change the parent (which was the class static) to the class instance
143:                // We really need to check if we're a static inner class here first...
144:                // but for some reason Java won't show the static modifier on our
145:                // fake inner classes...  could generate a flag field.
146:                if (instanceNameSpace != null
147:                        && className.startsWith(instanceNameSpace.getName()
148:                                + "$")) {
149:                    try {
150:                        ClassGenerator.getClassGenerator()
151:                                .setInstanceNameSpaceParent(obj, className,
152:                                        instanceNameSpace);
153:                    } catch (UtilEvalError e) {
154:                        throw e.toEvalError(this , callstack);
155:                    }
156:                }
157:
158:                return obj;
159:            }
160:
161:            // TODO
162:            /*
163:            	This is totally broken...
164:            	need to construct a real inner class block here...
165:             */
166:            private Object constructWithClassBody(Class type, Object[] args,
167:                    BSHBlock block, CallStack callstack, Interpreter interpreter)
168:                    throws EvalError {
169:                //throw new InterpreterError("constructWithClassBody unimplemented");
170:
171:                String name = callstack.top().getName() + "$"
172:                        + (++innerClassCount);
173:                Modifiers modifiers = new Modifiers();
174:                modifiers.addModifier(Modifiers.CLASS, "public");
175:                Class clas;
176:                try {
177:                    clas = ClassGenerator.getClassGenerator().generateClass(
178:                            name, modifiers, null/*interfaces*/,
179:                            type/*superClass*/,
180:                            // block is not innerClassBlock here!!!
181:                            block, false/*isInterface*/, callstack,
182:                            interpreter);
183:                } catch (UtilEvalError e) {
184:                    throw e.toEvalError(this , callstack);
185:                }
186:                try {
187:                    return Reflect.constructObject(clas, args);
188:                } catch (Exception e) {
189:                    if (e instanceof  InvocationTargetException)
190:                        e = (Exception) ((InvocationTargetException) e)
191:                                .getTargetException();
192:                    if (Interpreter.DEBUG)
193:                        e.printStackTrace();
194:                    throw new EvalError(
195:                            "Error constructing inner class instance: " + e,
196:                            this , callstack);
197:                }
198:            }
199:
200:            private Object constructWithInterfaceBody(Class type,
201:                    Object[] args, BSHBlock body, CallStack callstack,
202:                    Interpreter interpreter) throws EvalError {
203:                NameSpace namespace = callstack.top();
204:                NameSpace local = new NameSpace(namespace, "AnonymousBlock");
205:                callstack.push(local);
206:                body.eval(callstack, interpreter, true/*overrideNamespace*/);
207:                callstack.pop();
208:                // statical import fields from the interface so that code inside
209:                // can refer to the fields directly (e.g. HEIGHT)
210:                local.importStatic(type);
211:                try {
212:                    return local.getThis(interpreter).getInterface(type);
213:                } catch (UtilEvalError e) {
214:                    throw e.toEvalError(this , callstack);
215:                }
216:            }
217:
218:            private Object objectArrayAllocation(BSHAmbiguousName nameNode,
219:                    BSHArrayDimensions dimensionsNode, CallStack callstack,
220:                    Interpreter interpreter) throws EvalError {
221:                NameSpace namespace = callstack.top();
222:                Class type = nameNode.toClass(callstack, interpreter);
223:                if (type == null)
224:                    throw new EvalError("Class " + nameNode.getName(namespace)
225:                            + " not found.", this , callstack);
226:
227:                return arrayAllocation(dimensionsNode, type, callstack,
228:                        interpreter);
229:            }
230:
231:            private Object primitiveArrayAllocation(BSHPrimitiveType typeNode,
232:                    BSHArrayDimensions dimensionsNode, CallStack callstack,
233:                    Interpreter interpreter) throws EvalError {
234:                Class type = typeNode.getType();
235:
236:                return arrayAllocation(dimensionsNode, type, callstack,
237:                        interpreter);
238:            }
239:
240:            private Object arrayAllocation(BSHArrayDimensions dimensionsNode,
241:                    Class type, CallStack callstack, Interpreter interpreter)
242:                    throws EvalError {
243:                /*
244:                	dimensionsNode can return either a fully intialized array or VOID.
245:                	when VOID the prescribed array dimensions (defined and undefined)
246:                	are contained in the node.
247:                 */
248:                Object result = dimensionsNode.eval(type, callstack,
249:                        interpreter);
250:                if (result != Primitive.VOID)
251:                    return result;
252:                else
253:                    return arrayNewInstance(type, dimensionsNode, callstack);
254:            }
255:
256:            /**
257:            	Create an array of the dimensions specified in dimensionsNode.
258:            	dimensionsNode may contain a number of "undefined" as well as "defined"
259:            	dimensions.
260:            	<p>
261:
262:            	Background: in Java arrays are implemented in arrays-of-arrays style
263:            	where, for example, a two dimensional array is a an array of arrays of
264:            	some base type.  Each dimension-type has a Java class type associated 
265:            	with it... so if foo = new int[5][5] then the type of foo is 
266:            	int [][] and the type of foo[0] is int[], etc.  Arrays may also be 
267:            	specified with undefined trailing dimensions - meaning that the lower 
268:            	order arrays are not allocated as objects. e.g.  
269:            	if foo = new int [5][]; then foo[0] == null //true; and can later be 
270:            	assigned with the appropriate type, e.g. foo[0] = new int[5];
271:            	(See Learning Java, O'Reilly & Associates more background).
272:            	<p>
273:
274:            	To create an array with undefined trailing dimensions using the
275:            	reflection API we must use an array type to represent the lower order
276:            	(undefined) dimensions as the "base" type for the array creation... 
277:            	Java will then create the correct type by adding the dimensions of the 
278:            	base type to specified allocated dimensions yielding an array of
279:            	dimensionality base + specified with the base dimensons unallocated.  
280:            	To create the "base" array type we simply create a prototype, zero 
281:            	length in each dimension, array and use it to get its class 
282:            	(Actually, I think there is a way we could do it with Class.forName() 
283:            	but I don't trust this).   The code is simpler than the explanation...
284:            	see below.
285:             */
286:            private Object arrayNewInstance(Class type,
287:                    BSHArrayDimensions dimensionsNode, CallStack callstack)
288:                    throws EvalError {
289:                if (dimensionsNode.numUndefinedDims > 0) {
290:                    Object proto = Array.newInstance(type,
291:                            new int[dimensionsNode.numUndefinedDims]); // zeros
292:                    type = proto.getClass();
293:                }
294:
295:                try {
296:                    return Array.newInstance(type,
297:                            dimensionsNode.definedDimensions);
298:                } catch (NegativeArraySizeException e1) {
299:                    throw new TargetError(e1, this , callstack);
300:                } catch (Exception e) {
301:                    throw new EvalError("Can't construct primitive array: "
302:                            + e.getMessage(), this, callstack);
303:                }
304:            }
305:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.