Popular Posts
javax.net.ssl.SSLHandshakeException: Connection closed by peer in Android 5.0 Lollipop Recently, there is a error occurs when access website via ssl connection like below although it worked fine several days ago. // Enable SSL... Enable SSL connection for Jsoup import org.jsoup.Connection; import org.jsoup.Jsoup; import javax.net.ssl.*; import java.io.IOException; import java.security.KeyManagement... Build an OpenVPN server on android device Preparation An android device, in this case, Sony xperia Z is used Root permission required Linux Deploy for deploy i...
Stats
Compile source via JavaCompiler
  1. import javax.tools.*;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.io.PrintWriter;
  5. import java.io.StringWriter;
  6. import java.lang.reflect.InvocationTargetException;
  7. import java.net.URI;
  8. import java.net.URL;
  9. import java.net.URLClassLoader;
  10. import java.util.Arrays;
  11.  
  12. /**
  13.  * Created by nanashi07 on 15/12/13.
  14.  */
  15. public class CompileOnFly {
  16.  
  17.     public static void main(String args[]) throws IOException {
  18.         JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  19.         DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
  20.  
  21.         StringWriter writer = new StringWriter();
  22.         PrintWriter out = new PrintWriter(writer);
  23.         out.println("package com.prhythm.output;");
  24.         out.println();
  25.         out.println("public class OutputImpl implements IOutput {");
  26.         out.println();
  27.         out.println("   public void printFor(String message) {");
  28.         out.println("       System.out.printf(\"Print from %s : %s%n\", getClass().getName(), message);");
  29.         out.println("   }");
  30.         out.println();
  31.         out.println("}");
  32.         out.close();
  33.         JavaFileObject file = new TextJavaObject("com.prhythm.output.OutputImpl", writer.toString());
  34.  
  35.         Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file);
  36.         JavaCompiler.CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits);
  37.  
  38.         boolean success = task.call();
  39.         for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
  40.             System.out.printf("Code: %s%n", diagnostic.getCode());
  41.             System.out.printf("Kind: %s%n", diagnostic.getKind());
  42.             System.out.printf("Position: %s%n", diagnostic.getPosition());
  43.             System.out.printf("StartPosition: %s%n", diagnostic.getStartPosition());
  44.             System.out.printf("EndPosition: %s%n", diagnostic.getEndPosition());
  45.             System.out.printf("Source: %s%n", diagnostic.getSource());
  46.             System.out.printf("Message: %s%n", diagnostic.getMessage(null));
  47.         }
  48.  
  49.         if (success) {
  50.             try {
  51.                 URLClassLoader classLoader = URLClassLoader.newInstance(new URL[]{new File("").toURI().toURL()});
  52.                 Class<?> outClass = Class.forName("com.prhythm.output.OutputImpl", true, classLoader);
  53.                 Object outInstance = outClass.newInstance();
  54.                 outClass.getDeclaredMethod("printFor", new Class[]{String.class}).invoke(outInstance, "Bruce");
  55.             } catch (ClassNotFoundException e) {
  56.                 System.err.println("Class not found: " + e);
  57.             } catch (NoSuchMethodException e) {
  58.                 System.err.println("No such method: " + e);
  59.             } catch (IllegalAccessException e) {
  60.                 System.err.println("Illegal access: " + e);
  61.             } catch (InvocationTargetException e) {
  62.                 System.err.println("Invocation target: " + e);
  63.             } catch (InstantiationException e) {
  64.                 System.err.println("Initialize instance: " + e);
  65.             }
  66.         }
  67.     }
  68. }
  69.  
  70. class TextJavaObject extends SimpleJavaFileObject {
  71.     final String code;
  72.  
  73.     TextJavaObject(String name, String code) {
  74.         super(URI.create("string:///" + name.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE);
  75.         this.code = code;
  76.     }
  77.  
  78.     @Override
  79.     public CharSequence getCharContent(boolean ignoreEncodingErrors) {
  80.         return code;
  81.     }
  82. }

Output:

  1. Print from com.prhythm.output.OutputImpl : Bruce
Annotation processor on Intellij IDEA
Project structure
+ ---- annotation- processor
| + ---- annotation- lib
|   + ---- build.gradle
|   + ---- src
|     + ---- main
|     | + ---- java
|     |   + ---- com
|     |     + ---- prhythm
|     |       + ---- annotations
|     |         + ---- PrintUsage.java
|     |         + ---- PrintUsageProcessor.java
|     | + ---- resources
|         + ---- META-INF
|           + ---- services
|             + ---- javax.annotation.processing.Processor
| + ---- foo
|   + ---- build.gradle
|   + ---- src
|     + ---- main
|       + ---- java
|         + ---- com
|           + ---- prhythm
|             + ---- foo
|               + ---- Bar.java
| + ---- build.gradle
| + ---- settings.gradle

PrintUsage.java
  1. package com.prhythm.annotations;
  2.  
  3. /**
  4. * Print usage
  5. * Created by nanashi07 on 15/12/2.
  6. */
  7. public @interface PrintUsage {
  8. }

PrintUsageProcessor.java
  1. package com.prhythm.annotations;
  2.  
  3. import javax.annotation.processing.AbstractProcessor;
  4. import javax.annotation.processing.Messager;
  5. import javax.annotation.processing.RoundEnvironment;
  6. import javax.annotation.processing.SupportedAnnotationTypes;
  7. import javax.lang.model.element.Element;
  8. import javax.lang.model.element.TypeElement;
  9. import javax.tools.Diagnostic;
  10. import java.util.Set;
  11.  
  12. /**
  13. * Processor of {@link PrintUsage}
  14. * Created by nanashi07 on 15/12/2.
  15. */
  16. @SupportedAnnotationTypes("com.prhythm.annotations.PrintUsage")
  17. public class PrintUsageProcessor extends AbstractProcessor {
  18. @Override
  19. public boolean process(Set annotations, RoundEnvironment roundEnv) {
  20. Messager messager = processingEnv.getMessager();
  21. for (TypeElement typeElement : annotations) {
  22. for (Element element : roundEnv.getElementsAnnotatedWith(typeElement)) {
  23. String msg = String.format("Use %s on %s#%s", typeElement, element.getEnclosingElement(), element);
  24. messager.printMessage(Diagnostic.Kind.NOTE, msg);
  25. }
  26. }
  27. return true;
  28. }
  29. }

javax.annotation.processing.Processor
  1. com.prhythm.annotations.PrintUsageProcessor

Bar.java
  1. package com.prhythm.foo;
  2.  
  3. import com.prhythm.annotations.PrintUsage;
  4.  
  5. /**
  6. * Test class
  7. * Created by nanashi07 on 15/12/2.
  8. */
  9. public class Bar {
  10.  
  11. @PrintUsage
  12. public void move(String name) {
  13.  
  14. }
  15.  
  16. @PrintUsage
  17. public long time() {
  18. return System.currentTimeMillis();
  19. }
  20.  
  21. }

build.gradle (foo)
  1. group 'com.prhythm'
  2. version '1.0-SNAPSHOT'
  3.  
  4. apply plugin: 'java'
  5.  
  6. sourceCompatibility = 1.6
  7.  
  8. repositories {
  9. mavenCentral()
  10. }
  11.  
  12. dependencies {
  13. testCompile group: 'junit', name: 'junit', version: '4.11'
  14. compile project(':annotation-lib')
  15. }

Enable annotation processor on preference




Build with gradle

  1. gradle clean build

result


References:



Type Memo

Note: ==================================================
Note: TypeElement: com.prhythm.annotations.PrintUsage
Note: TypeElement.getClass(): class com.sun.tools.javac.code.Symbol$ClassSymbol
Note: TypeElement.getSimpleName(): PrintUsage
Note: TypeElement.getEnclosedElements(): 
Note: TypeElement.getEnclosingElement(): com.prhythm.annotations
Note: TypeElement.getInterfaces(): java.lang.annotation.Annotation
Note: TypeElement.getNestingKind(): TOP_LEVEL
Note: TypeElement.getQualifiedName(): com.prhythm.annotations.PrintUsage
Note: TypeElement.getSuperclass(): none
Note: TypeElement.getTypeParameters(): 
Note: TypeElement.getAnnotationMirrors(): 
Note: TypeElement.asType(): com.prhythm.annotations.PrintUsage
Note: TypeElement.getKind(): ANNOTATION_TYPE
Note: TypeElement.getModifiers(): [public, abstract]
Note: ----------------------------------------------------------
Note: Element: move(java.lang.String)
Note: Element.getModifiers(): [public]
Note: Element.getClass(): class com.sun.tools.javac.code.Symbol$MethodSymbol
Note: Element.getKind(): METHOD
Note: Element.getAnnotationMirrors(): @com.prhythm.annotations.PrintUsage
Note: Element.getSimpleName(): move
Note: Element.asType(): (java.lang.String)void
Note: Element.getEnclosedElements(): 
Note: Element.getEnclosingElement(): com.prhythm.foo.Bar
Note: ----------------------------------------------------------
Note: Element: time()
Note: Element.getModifiers(): [public]
Note: Element.getClass(): class com.sun.tools.javac.code.Symbol$MethodSymbol
Note: Element.getKind(): METHOD
Note: Element.getAnnotationMirrors(): @com.prhythm.annotations.PrintUsage
Note: Element.getSimpleName(): time
Note: Element.asType(): ()long
Note: Element.getEnclosedElements(): 
Note: Element.getEnclosingElement(): com.prhythm.foo.Bar
Note: ==================================================
Note: TypeElement: com.prhythm.annotations.Mark
Note: TypeElement.getClass(): class com.sun.tools.javac.code.Symbol$ClassSymbol
Note: TypeElement.getSimpleName(): Mark
Note: TypeElement.getEnclosedElements(): value(),names()
Note: TypeElement.getEnclosingElement(): com.prhythm.annotations
Note: TypeElement.getInterfaces(): java.lang.annotation.Annotation
Note: TypeElement.getNestingKind(): TOP_LEVEL
Note: TypeElement.getQualifiedName(): com.prhythm.annotations.Mark
Note: TypeElement.getSuperclass(): none
Note: TypeElement.getTypeParameters(): 
Note: TypeElement.getAnnotationMirrors(): 
Note: TypeElement.asType(): com.prhythm.annotations.Mark
Note: TypeElement.getKind(): ANNOTATION_TYPE
Note: TypeElement.getModifiers(): [public, abstract]
Note: ----------------------------------------------------------
Note: Element: com.prhythm.foo.Yahoo
Note: Element.getModifiers(): [public, abstract]
Note: Element.getClass(): class com.sun.tools.javac.code.Symbol$ClassSymbol
Note: Element.getKind(): INTERFACE
Note: Element.getAnnotationMirrors(): @com.prhythm.annotations.Mark("2323")
Note: Element.getSimpleName(): Yahoo
Note: Element.asType(): com.prhythm.foo.Yahoo
Note: Element.getEnclosedElements(): home(java.lang.String)
Note: Element.getEnclosingElement(): com.prhythm.foo
Note: ----------------------------------------------------------
Note: Element: home(java.lang.String)
Note: Element.getModifiers(): [public, abstract]
Note: Element.getClass(): class com.sun.tools.javac.code.Symbol$MethodSymbol
Note: Element.getKind(): METHOD
Note: Element.getAnnotationMirrors(): @com.prhythm.annotations.Mark("110"),@com.prhythm.core.generic.http.annotation.Get("https://tw.yahoo.com")
Note: Element.getSimpleName(): home
Note: Element.asType(): (java.lang.String)java.lang.String
Note: Element.getEnclosedElements(): 
Note: Element.getEnclosingElement(): com.prhythm.foo.Yahoo