GET Custom Annotation Preprocessor - creating an Android-based application and configuration in IntelliJ IDEA / Sudo Null IT News FREE

Hello!

Recently, I was faced with the task of writing my own custom annotations and processing them during compiling. The offse motion I asked myself: where to start? After the analysis, I distinct to share with you the answer to this interrogation.
I think information technology makes no sense to tell apart what annotations are in java and what they are eaten with, as every puppyish programmer is familiar with this (and who is not known with it, atomic number 2 can learn information technology on his own). To boot, there is an interesting investigatory article on this phenomenon.
But today I want to talk specifically nigh custom annotations in an Android application that are processed during the compilation of the projection aside your own handler and about auto-generation of classes supported them. And also, on the room, I'll tell you how to quickly configure everything in Mind (I myself use version 12.1, maybe there are differences in others).

For implementation, we need 2 projects: in the primary, we will describe our custom annotations and their coach, from it we will generate a jar file out, which we leave connect to the second gear essa protrude, which will use our annotations.

Step 1

We create a hot library project in which we depict our notation. An annotated year looks something like this:

          @Mark(ElementType.Method acting) @Keeping(RetentionPolicy.Reservoir) public @interface CustomAnnotation {     String className();     Twine value() default "Hello";     int type() default on 0; }                  

@Keeping says that our notation volition live present only in the source code and discarded by the compiler (and until that moment we leave action it).

Step 2

We make over our note processor directly. Information technology is a category that extends AbstractProcessor. We distinguish him that he will process all annotations and signal the supported version of the source files in this way:

          @SupportedAnnotationTypes({"*"}) @SupportedSourceVersion(SourceVersion.RELEASE_6) public class CustomProcessor extends AbstractProcessor {  }                  

Next, we redefine the outgrowth method, in which we order the logic for generating a new class. My method looks equivalent this:

          @Override     unexclusive boolean process(Set annotations, RoundEnvironment roundEnv) {         for (Element e : roundEnv.getElementsAnnotatedWith(CustomAnnotation.class)) {             CustomAnnotation ca = e.getAnnotation(CustomAnnotation.class);             String name = e.getSimpleName().toString();             char[] c = name.toCharArray();             c[0] = Character.toUpperCase(c[0]);             name = fres String(name);             TypeElement clazz = (TypeElement) e.getEnclosingElement();             examine {                 JavaFileObject f = processingEnv.getFiler().                         createSourceFile(clazz.getQualifiedName() + "Autogenerate");                 processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE,                         "Creating " + f.toUri());                 Writer w = f.openWriter();                 try {                     String pack = clazz.getQualifiedName().toString();                     PrintWriter pw = parvenu PrintWriter(w);                     pw.println("package "                             + pack.substring(0, load down.lastIndexOf('.')) + ";");                     pw.println("\npublic assort "                             + clazz.getSimpleName() + "Autogenerate {");                     TypeMirror type = e.asType();                     pw.println("\n    public " + ca.className() + " result = \"" + ca.esteem() + "\";");                     pw.println("    public int type = " + ca.type() + ";");                     pw.println("\n    snug " + clazz.getSimpleName()                             + "Autogenerate() {}");                     pw.println("\n    /** Handle something. */");                     pw.println("    weatherproof final void plow" + name                             + "(" + ca.className() + " value" + ") {");                     pw.println("\n//" + e);                     pw.println("//" + ca);                     pw.println("\n        System.out.println(value);");                     pw.println("    }");                     pw.println("}");                     pw.flush();                 } finally {                     w.close();                 }             } catch (IOException x) {                 processingEnv.getMessager().printMessage(Diagnostic.Kind.Erroneous belief,                         x.toString());             }         }         return reliable;     }                  

At this represent, you can commove fantasy and pen what your pith desires (healed, Beaver State what is required =). Afterward you have polished with the annotation processor and described all your custom annotations, you need to generate a jar file from this project. In Idea 12, this is done quite a simply: Project Settings -> Artifacts -> Add -> Jar -> From modules ... Next, do the Build -> Rebuild Project and find our generated jar file in the Yield directory of the project.

Step 3

We make a test project in which we will use our custom annotations. We connect the jar file generated at the last pace to the project and are glad that our annotations are in real time procurable to us. In any class, write our notation, e.g. like this:

          public socio-economic class MyActivity extends Activity {     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.main);     }     @CustomAnnotation(className = "Thread", type = 1)     public void annotatedMethod(Strand value) {     } }                  

Remember that we indicated our annotation @Target(ElementType.METHOD), which substance that we can register it only before the method.

Pace 4

Now let's say Musical theme use our note processor and the magic wish start working! To do this, work to Settings in the Compiler -> Note Processors incision . We tick Enable annotation processing , in the Processor itinerary field narrow the path to our generated shake up Indian file. Also in the Processor FQ name window, enter the full refer of the family that is responsible for processing. In our case, this is a CustomProcessor. A filled window should look on something like this.

Step 5

We do the Build -> Rebuild project and enjoy the results. The generated folder should seem in the project tree diagram, in which new files leave lie.
Here's what I got:

          public class MyActivityAutogenerate {     public String result = "Howdy";     public int type = 1;     protected MyActivityAutogenerate() {}     /** Handle something. */     protected final void handleannotatedMethod(String value) { //annotatedMethod(java.lang.String) //@com.example.AnnotationsProcessor.CustomAnnotation(type=1, value=Hello, className=Draw)         System.out.println(value);     } }                  

Happy codding!

DOWNLOAD HERE

GET Custom Annotation Preprocessor - creating an Android-based application and configuration in IntelliJ IDEA / Sudo Null IT News FREE

Posted by: thompsonusen2002.blogspot.com

0 Response to "GET Custom Annotation Preprocessor - creating an Android-based application and configuration in IntelliJ IDEA / Sudo Null IT News FREE"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel