jeudi 29 septembre 2022

Java Annotation Processor handle modified source code positions

I'm writing custom annotation processor and got struggling with code elements' positions.

Imagine I have the code:

    public class DummyStepClass {

        @Step
        public void getInfo() throws Exception {
            HttpClient client = HttpClient.newBuilder().build();
            @Remember("REQUEST") HttpRequest request = HttpRequest.newBuilder()
                    .uri(new URI("https://postman-echo.com/get"))
                    .GET()
                    .build();
            @Remember("RESPONSE") HttpResponse<String> response = 
                    client.send(request, HttpResponse.BodyHandlers.ofString());
            System.out.println(response.statusCode());
            System.out.println(response.body());
        }
    }

Purpose of annotation is to save variable into context of a program flow through my steps.

Context class:

    public class Context {

        private static final HashMap<String, Object> storage = new LinkedHashMap<>();

        private Context() {}

        public static void save(String k, Object v) {
            storage.put(k, v);
        }
    }

Literally I want to achieve invoking Context.save(k, v); when annotated rather than writing it every time.

So as a result I want to have something like this:

    public class DummyStepClass {

        @Step
        public void getInfo() throws Exception {
            HttpClient client = HttpClient.newBuilder().build();
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(new URI("https://postman-echo.com/get"))
                    .GET()
                    .build();
            Context.save("REQUEST", request);
            HttpResponse<String> response =
                    client.send(request, HttpResponse.BodyHandlers.ofString());
            Context.save("RESPONSE", request);
            System.out.println(response.statusCode());
            System.out.println(response.body());
    }
}

I do generate this lines of code and they appears in .class files. However this two statements are added in the end of a method.

How can I handle this?





Aucun commentaire:

Enregistrer un commentaire