01: /*
02: * @(#)setFinalizer.java 1.2 04/12/06
03: *
04: * Copyright (c) 1997-2004 Sun Microsystems, Inc. All Rights Reserved.
05: *
06: * See the file "LICENSE.txt" for information on usage and redistribution
07: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
08: */
09: package org.pnuts.lib;
10:
11: import pnuts.lang.PnutsFunction;
12: import pnuts.lang.Context;
13: import pnuts.lang.Runtime;
14:
15: /*
16: * function setFinalizer(target, func())
17: */
18: public class setFinalizer extends PnutsFunction {
19:
20: private final static Object[] NO_ARGS = new Object[] {};
21: private final static String FINALIZER_KEY = "pnuts.lib.setFinalizer.key"
22: .intern();
23:
24: public setFinalizer() {
25: super ("setFinalizer");
26: }
27:
28: public boolean defined(int nargs) {
29: return nargs == 2;
30: }
31:
32: private static Runnable getFinalizeCommand(
33: final PnutsFunction func, final Context context) {
34: final Thread currentThread = Thread.currentThread();
35: final ClassLoader ccl = currentThread.getContextClassLoader();
36: final ClassLoader cl = context.getClassLoader();
37: final Context ctx = (Context) context.clone();
38: return new Runnable() {
39: public void run() {
40: currentThread.setContextClassLoader(ccl);
41: context.setClassLoader(cl);
42: func.call(NO_ARGS, ctx);
43: }
44: };
45: }
46:
47: protected Object exec(Object args[], Context context) {
48: if (args.length != 2) {
49: undefined(args, context);
50: }
51: Object target = args[0];
52: PnutsFunction func = (PnutsFunction) args[1];
53: Runnable cmd = getFinalizeCommand(func, context);
54: Runtime.setElement(target, FINALIZER_KEY, Cleaner.create(
55: target, cmd), context);
56: return null;
57: }
58:
59: public String toString() {
60: return "function setFinalizer(target, func())";
61: }
62: }
|