rainash
rainash

Reputation: 874

How to generate code when compiling

Is there any way to generate code when compiling. For example: I write an Activity

public class XXActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        doSomething();
    }

    private void doSomething() {

    }
}

I want to log the time before and after method doSomething():

public class XXActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        Log.i("XX", "start:" + System.currentTimeMillis()); // auto generate when compiling
        doSomething();
        Log.i("XX", "finish:" + System.currentTimeMillis()); // auto generate when compiling
    }

    private void doSomething() {

    }
}

How to achieve the effect like example above, any idea is appreciated.

Upvotes: 1

Views: 56

Answers (1)

Andrii Omelchenko
Andrii Omelchenko

Reputation: 13343

You should create custom annotation. For beginning take look at this tutorial:

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
   StringBuilder builder = new StringBuilder()
           .append("package com.stablekernel.annotationprocessor.generated;nn")
           .append("public class GeneratedClass {nn") // open class
           .append("tpublic String getMessage() {n") // open method
           .append("ttreturn "");


   // for each javax.lang.model.element.Element annotated with the CustomAnnotation
   for (Element element : roundEnv.getElementsAnnotatedWith(CustomAnnotation.class)) {
       String objectType = element.getSimpleName().toString();



       // this is appending to the return statement
       builder.append(objectType).append(" says hello!\n");
   }


   builder.append("";n") // end return
           .append("t}n") // close method
           .append("}n"); // close class



   try { // write the file
       JavaFileObject source = processingEnv.getFiler().createSourceFile("com.stablekernel.annotationprocessor.generated.GeneratedClass");


       Writer writer = source.openWriter();
       writer.write(builder.toString());
       writer.flush();
       writer.close();
   } catch (IOException e) {
       // Note: calling e.printStackTrace() will print IO errors
       // that occur from the file already existing after its first run, this is normal
   }

   return true;
}

Upvotes: 2

Related Questions