public class Closure<R>
{
protected R result;
public R eval
() {
this.
result=newInstance
().
result;
return result;
}
private Closure<R> newInstance
() {
try {
final Constructor syntheticConstructor = getClass
().
getDeclaredConstructors()[0];
return (Closure<R>
) syntheticConstructor.
newInstance(createParams
());
} catch (Exception e
) {
throw new RuntimeException("Error creating new instance of closure", e
);
}
}
private Object[] createParams
() throws IllegalAccessException {
final Field[] fields = getClass
().
getDeclaredFields();
final int fieldCount = fields.
length;
final Object[] params =
new Object[fieldCount
];
params
[0] = fields
[fieldCount -
1].
get(this);
// enclosing Instance
for (int i = fieldCount -
2; i >=
0; i--
) {
params
[i +
1] = fields
[i
].
get(this);
}
return params;
}
}