01: /*
02: * JavaCastCmd.java
03: *
04: * Implements the built-in "java::cast" command.
05: *
06: * Copyright (c) 1998 Mo DeJong.
07: *
08: * See the file "license.terms" for information on usage and
09: * redistribution of this file, and for a DISCLAIMER OF ALL
10: * WARRANTIES.
11: *
12: * RCS: @(#) $Id: JavaCastCmd.java,v 1.4 2006/04/13 07:36:50 mdejong Exp $
13: *
14: */
15:
16: package tcl.lang;
17:
18: import tcl.lang.reflect.PkgInvoker;
19:
20: /**
21: * Implements the built-in "java::cast" command.
22: */
23:
24: class JavaCastCmd implements Command {
25:
26: /*----------------------------------------------------------------------
27: *
28: * cmdProc --
29: *
30: * This procedure is invoked to process the "java::cast" Tcl
31: * command. See the user documentation for details on what it
32: * does.
33: *
34: * Results:
35: * None.
36: *
37: * Side effects:
38: * A standard Tcl result is stored in the interpreter.
39: *
40: *----------------------------------------------------------------------
41: */
42:
43: public void cmdProc(Interp interp, // Current interpreter.
44: TclObject argv[]) // Argument list.
45: throws TclException // A standard Tcl exception.
46: {
47:
48: if (argv.length != 3) {
49: throw new TclNumArgsException(interp, 1, argv,
50: "class javaObj");
51: }
52:
53: Class cast_to = ClassRep.get(interp, argv[1]);
54:
55: // A cast to an inaccessible type is not legal in Java.
56: if (!PkgInvoker.isAccessible(cast_to)) {
57: JavaInvoke.notAccessibleError(interp, cast_to);
58: }
59:
60: Object obj = ReflectObject.get(interp, argv[2]);
61:
62: // The null object can be cast to any type
63: if (obj == null) {
64: interp.setResult(ReflectObject.newInstance(interp, cast_to,
65: obj));
66: return;
67: }
68:
69: Class cast_from = obj.getClass();
70:
71: if (cast_to.isAssignableFrom(cast_from)) {
72: interp.setResult(ReflectObject.newInstance(interp, cast_to,
73: obj));
74: return;
75: }
76:
77: // The JavaInfoCmd.getNameFromClass() method will return the name
78: // of an Array class in a human readable form.
79:
80: throw new TclException(interp, "could not cast from "
81: + JavaInfoCmd.getNameFromClass(cast_from) + " to "
82: + JavaInfoCmd.getNameFromClass(cast_to));
83: }
84:
85: } // end JavaCastCmd
|