1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.millscript.millscript.functions;
23
24 import org.millscript.millscript.alert.Alerts;
25 import org.millscript.millscript.vm.Machine;
26
27 import java.lang.reflect.Constructor;
28
29 /**
30 * This class implements a function which invokes one of several Java
31 * constructors to create a new instance of a Java class. The exact Java
32 * constructor that is invoked depends on the number of arguments supplied when
33 * this function is called.
34 */
35 public final class JOConstructor extends Function {
36
37 /**
38 * The array of constructors to choose from, linking the number of
39 * arguments(position in the array) to the Java constructor to be called.
40 */
41 private final JConstructor[] jconstructors;
42
43 /**
44 * Constructs a new <code>JOConstructor</code> function to invoke one of
45 * the specified Java constructors.
46 *
47 * @param cons the array of Java constructors to choose from
48 */
49 public JOConstructor( final Constructor[] cons ) {
50 jconstructors = new JConstructor[ cons.length ];
51 for ( int i = 0; i < cons.length; i++ ) {
52 Constructor c = cons[ i ];
53 if ( c != null ) {
54 jconstructors[ i ] = new JConstructor( c );
55 }
56 }
57 }
58
59 /**
60 * @see org.millscript.millscript.functions.Function#apply(org.millscript.millscript.vm.Machine, int)
61 */
62 @Override
63 public void apply( final Machine mc, final int nargs ) {
64 try {
65 JConstructor jc = jconstructors[ nargs ];
66 if ( jc == null ) {
67 throw(
68 Alerts.fault( "No constructors" ).mishap()
69 );
70 }
71 jc.apply( mc, nargs );
72 } catch ( IndexOutOfBoundsException ex ) {
73 throw(
74 Alerts.eval(
75 "No constructor with this arity",
76 null
77 ).culprit( "arity", new Integer( nargs ) ).mishap()
78 );
79 }
80 }
81
82 }