4

如何记录在运行时传递给方法的参数?是否有任何 Java 库为此或可以引发任何异常来监视它?

4

3 回答 3

5

您可以使用 javassist 的ProxyFactoryTranslator更改以在运行时打印参数:


使用Translator(带有新的ClassLoader):

public static class PrintArgumentsTranslator implements Translator {

    public void start(ClassPool pool) {}

    @Override
    public void onLoad(ClassPool pool, String cname)
            throws NotFoundException, CannotCompileException {
        CtClass c = pool.get(cname);

        for (CtMethod m : c.getDeclaredMethods()) 
            insertLogStatement(c, m);
        for (CtConstructor m : c.getConstructors())
            insertLogStatement(c, m);
    }

    private void insertLogStatement(CtClass c, CtBehavior m) {
        try {
            List<String> args = new LinkedList<String>();
            for (int i = 0; i < m.getParameterTypes().length; i++)
                args.add("$" + (i + 1));

            String toPrint = 
                "\"----- calling: "+c.getName() +"." + m.getName() 
                + args.toString()
                .replace("[", "(\" + ")
                .replace(",", " + \", \" + ")
                .replace("]", "+\")\""); 
            m.insertBefore("System.out.println("+toPrint+");");
        } catch (Exception e) { 
            // ignore any exception (we cannot insert log statement)
        }
    }
}

*请注意,您需要更改默认值ClassLoader,以便您可以检测类,因此在调用您之前,main您需要插入以下代码:

public static void main(String[] args) throws Throwable {
    ClassPool cp = ClassPool.getDefault();
    Loader cl = new Loader(cp);
    cl.addTranslator(cp, new PrintArgumentsTranslator());
    cl.run("test.Test$MyApp", args);  // or whatever class you want to start with
}

public class MyApp {

    public MyApp() {
        System.out.println("Inside: MyApp constructor");
    }

    public static void main(String[] args) {
        System.out.println("Inside: main method");
        new MyApp().method("Hello World!", 4711);
    }

    public void method(String string, int i) {
        System.out.println("Inside: MyApp method");
    }
}

输出:

----- calling: test.Test$MyApp.main([Ljava.lang.String;@145e044)
Inside: main method
----- calling: test.Test$MyApp.Test$MyApp()
Inside: MyApp constructor
----- calling: test.Test$MyApp.method(Hello World!, 4711)
Inside: MyApp method

使用ProxyFactory

public class Test {

    public String method(String string, int integer) {
        return String.format("%s %d", string, integer);
    }

    public static void main(String[] args) throws Exception {

        ProxyFactory f = new ProxyFactory();
        f.setSuperclass(Test.class);

        Class<?> c = f.createClass();
        MethodHandler mi = new MethodHandler() {
            public Object invoke(
                    Object self, Method m, Method proceed, Object[] args)
                throws Throwable {

                System.out.printf("Method %s called with %s%n", 
                                  m.getName(), Arrays.toString(args));

                // call the original method
                return proceed.invoke(self, args);
            }
        };

        Test foo = (Test) c.newInstance();
        ((Proxy) foo).setHandler(mi);
        foo.method("Hello", 4711);
    }
}

输出:

Method method called with [Hello, 4711]
于 2012-06-20T07:06:52.480 回答
3

您应该尝试使用 AOP。这是一个或多或少做你想要的例子:How to use AOP with AspectJ for logging?

于 2012-06-20T07:15:18.993 回答
1

我认为您可以注册您的MBean然后只有您才能使用 JMX 进行检查。

链接: http ://docs.oracle.com/cd/E19159-01/819-7758/gcitp/index.html

于 2012-06-20T06:56:57.957 回答