1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
/*
* FreeArgsClass.oj
*
* Apr 29, 1999, by Michiaki Tatsubori
* Feb 2, 1999, by Michiaki Tatsubori
*/
package examples.freeargs;
import openjava.mop.*;
import openjava.ptree.*;
import openjava.syntax.*;
/**
* The metaclass <code>FreeArgsClass</code> provides classes with
* a facility of methods to accept unknown number of arguments.
* <p>
* For example, for the class:
* <pre>
* class MyCollection instantiates FreeArgsClass {
* public generous add( Object[] arg ) { .. }
* }
* </pre>
* We can use the class above as follows:
* <pre>
* MyCollection collection = ..;
* collection.add( a, b, null, c, d );
* </pre>
* <p>
*
* @author Michiaki Tatsubori
* @version 1.0
* @see java.lang.OJClass
*/
public class FreeArgsClass instantiates Metaclass extends OJClass
{
private static final String GENEROUS = "generous";
/** Translates definition */
public void translateDefinition() throws MOPException {
OJMethod[] methods = getDeclaredMethods();
for (int i = 0; i < methods.length; ++i) {
if (! methods[i].getModifiers().has( GENEROUS )) continue;
System.err.println( methods[i] );
OJClass[] paramtypes = methods[i].getParameterTypes();
if (paramtypes.length != 1 || ! paramtypes[0].isArray()) {
System.err.println( "illegal parameter, ignored." );
continue;
}
putMetaInfo( methods[i].getName(), paramtypes[0].getName() );
}
}
public OJMethod resolveException( NoSuchMemberException e,
String name, OJClass[] params )
throws NoSuchMemberException
{
try {
String argtypename = getMetaInfo( name );
if (argtypename != null) {
OJClass paramtype = OJClass.forName( argtypename );
return getMethod( name, new OJClass[]{ paramtype }, this );
}
} catch ( OJClassNotFoundException e2 ) {
System.err.println( e2 );
}
return super.resolveException( e, name, params );
}
/** Translates allocation parts */
public Expression expandMethodCall( Environment env, MethodCall expr ) {
String argtypename = getMetaInfo( expr.getName() );
if (argtypename == null) return expr;
OJClass comptype;
try {
comptype = OJClass.forName( argtypename ).getComponentType();
} catch ( OJClassNotFoundException e ) {
System.err.println( e );
return expr;
}
ExpressionList dim = new ExpressionList( null );
ArrayInitializer ainit = new ArrayInitializer( expr.getArguments() );
ArrayAllocationExpression carrier
= new ArrayAllocationExpression( comptype, dim, ainit );
expr.setArguments( new ExpressionList( carrier ) );
return expr;
}
public static boolean isRegisteredModifier( String keyword ) {
if (keyword.equals( GENEROUS )) return true;
return false;
}
}
|