alovaros
alovaros

Reputation: 476

How to read data of CtMethod

Greetings I'm would like to read the data of a method I try to change with Bytecode manipulation with javassist and a java agent. The reason is that my program (a webApplication) won't work (javassist.CannotCompileException: [source error] ) is missing what is this?) and no one could help me at the moment . So I wanna no what is inside my Methode maybe something produces a bug ... so I want to know if I can read and print the content of a CtMethod

My code

 private byte[] transformClass(Class classToTransform, byte[] b, String className) {
    if (className.startsWith("de/example")) {

        ClassPool pool = ClassPool.getDefault();
        CtClass cl = null;

        try {
                cl = pool.makeClass(new ByteArrayInputStream(b));

        } catch (IOException e) {
                e.printStackTrace();
        }


        try {


            assert cl != null;
            for (CtMethod ctMethod : cl.getMethods()) {
                changeMethod(ctMethod);
                System.out.println(ctMethod.getMethodInfo());
                System.out.println(ctMethod.getMethodInfo2());
            }

            b = cl.toBytecode();
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (cl != null) {
                cl.detach();
            }
        }
       }
    return b;
}

private void changeMethod(CtMethod method) throws NotFoundException, CannotCompileException {

    if (method.hasAnnotation(Loggable.class)) {
    System.out.println(method.getMethodInfo());
    System.out.println(method.getMethodInfo2());


    method.insertBefore(" startTime = 0;\n" +
            "   startTime = System.currentTimeMillis();\n" +
            "   final  de.example.webservice.ws.TestFolder.Logging threadLogger = de.example.webservice.ws.TestFolder.Logging.getInstance();\n" +
            "   Thread thread1 = new Thread(new Runnable(){\n" +
            "        @Override\n" +
            "        public void run() {\n" +
            "    threadLogger.info(\"Testlog\");\n" +
            "      try {\n" +
            "  threadLogger.logCall(Webservice.this.getClass().getMethod(\"startThread0\"),\"Thread\");\n" +
            "           } catch (Exception e) {\n" +
            "           e.printStackTrace();\n" +
            "         }\n" +
            "         }\n" +
            "              });\n" +
            "          thread1.start();");

    }
}

I just Methods at google who can read data from files like a .txt file but that isn't usefull for my problem.

Upvotes: 1

Views: 203

Answers (1)

Nicholas
Nicholas

Reputation: 16056

If you're trying to read the original source of the method, javassist doesn't really do that. You need a java bytecode decompiler. Google for that term. jad is a good one.

Upvotes: 2

Related Questions