SlideShare una empresa de Scribd logo
1 de 22
Descargar para leer sin conexión
JSUGA Tech Tips
Christoph Pickl, 2008-06-16
Compiler API
Compiler API
 “Compiling with the Java Compiler API”
   http://java.sun.com/mailers/techtips/corejava/2007/tt0307.html
 Standardized with Java6 (JSR-199)
   before com.sun.tools.javac.Main
     not standard, public programming interface
 Also compiles dependent classes
 Two possibilities: simple and advanced
   both will be covered in next slides
Compiler API - Simple - Roadmap


 Create    sourcecode
 (programatically created)
 Retrieve JavaCompiler
    via ToolProvider


 Invoke run      method
 Check    return code
    0 == successfull


 Get   class via reflection
    create instance, invoke

    methods, get/set fields, ...
Compiler API - Simple - The Source
 First of all: Create desired sourcecode
    Could be created dynamically
 Save it in right location
    Be aware of Eclipse’ standard src folder



package at.sitsolutions.techtips.s4666;

public class Hello {
  public static void sayHello() {
    System.out.println(“Hello TechTips!”);
  }
}
Compiler API - Simple - Compile it
package at.sitsolutions.techtips.s4666;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;

public class CompilerApi {
  public static void main(String[] args) {
    String path = “src/at/sitsolutions/techtips”
                  + “/s4666/Hello.java”;
    JavaCompiler compiler =
        ToolProvider.getSystemJavaCompiler();
    if(compiler.run(null, null, null, path) == 0) {
      // do something with fresh compiled class
    } else {
      System.err.println(“Ups, something went wrong!”);
    }
  }
}
Compiler API - Simple - Use it
 After compiling sourcecode...
    ... access class reflectively
    ... invoke static method

// assume we have compiled our sourcecode successfully

String className = “at.sitsolutions.techtips.s4666.Hello”;

try {
  Class<?> c = Class.forName(className);
  Method m = c.getDeclaredMethod(“sayHello”, new Class[] {});
  m.invoke(null, new Object[] {}); // prints “Hello TechTips”
} catch(Exception e) {
  e.printStackTrace();
}
Compiler API - Simple - Core Method

 The JavaCompiler.run method in detail:
   (actually inherited from javax.tools.Tool)
int run(
                      ... use null for System.in
 InputSream in,
                      ... use null for System.out
 OutputStream out,
                      ... use null for System.err
 OutputStream err,
                      ... files to compile
 String... args
);
Compiler API - Advanced
 Benefit of advanced version:
    Access to error messages
    More options (usefull if developing an IDE)
 Additionally involved classes:
    DiagnosticCollector, JavaFileObject,
     StandardJavaFileManager, CompilationTask

package at.sitsolutions.techtips.s4666;

public class Hello2 {
  public static void sayHello() {
    System.out.printnl(“Hello TechTips!”);
  }
}
Compiler API - Advanced - Compile it
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics =
    new DiagnosticCollector<JavaFileObject>();

StandardJavaFileManager manager =
    compiler.getStandardFileManager(diagnostics,
      Locale.ENGLISH, new ISO_8859_11());

String file=“src/at/sitsolutions/techtips/s4666/Hello2.java”;
Iterable<? extends JavaFileObject> compilationUnits =
    manager.getJavaFileObjects(new String[] {file});

CompilationTask task = compiler.getTask(null, manager,
                   diagnostics, null, null, compilationUnits);
if(task.call() == false) {
  // put error handling in here
}
manager.close();
Compiler API - Advanced - Error Handling
// error handling

for (Diagnostic d : diagnostics.getDiagnostics())
  System.out.printf(
    “Code: %s%nKind: %s%n” +
    “Position: %s (%s/%s)%n” +
    “Source: %s%nMessage: %s%n”, d.getCode(), d.getKind(),
    d.getPosition(), d.getStartPosition(), d.getEndPosition(),
    d.getSource(), d.getMessage(null));
}
/*
Code: compiler.err.cant.resolve.location
Kind: ERROR
Position: 123 (113/131)
Source: srcatsitsolutionstechtipss4666Hello2.java
Message: srcatsitsolutionstechtipss4666Hello2.java:5: ↵
   cannot find symbol
*/
Compiler API - Advanced - Core Method

  JavaCompiler.getTask method in detail:

CompilationTask getTask(
                        ... use null for System.err
   Writer out,
   JavaFileManager mgr, ... use null for compiler’s standard mgr
   DiagnosticListener lst, ... somehow mandatory
   Iterable<String> options, ... options to compiler
   Iterable<String> classes, ... used for annotation processing
   Iterable<? extends JavaFileObject>
                             ... files to compile
      compilationUnits
);
Compiler API - What for?


 Be     more dynamic
   Create classes on-the-fly
 
  Let application gain
   “experience”
 Build    your own IDE
   Provide meaningfull error
 
   messages
  Highlight specific error in
   sourcecode
 It’s   fun
Using printf
Using printf
 “Using printf with Customized Formattable Classes”
   http://blogs.sun.com/CoreJavaTechTips/entry/using_printf_with_customized_formattable

 Format output available since Java5
   well known from C language (%5.2f%n)
 Formattable interface
   formatTo(Formatter, int, int, int):void
   use locales, flags, width, precision
 Flags available:
   ALTERNATE (#), LEFT_JUSTIFY (-), UPPERCASE (^)
 Usage just as known from C language
Using printf - The Formattable Object
public class Alfa implements Formattable {
  private final String stamp12 =
    “ABCDEF123456”; // alternate
  private final String stamp24 =
    “ABCDEF123456GHIJKL123456”; // default

    public void formatTo(
     Formatter formatter, int flags, int width, int precision) {
      StringBuilder sb = new StringBuilder();

        //   1.   check flags (alternate)
        //   2.   set precision (cut off length)
        //   3.   check locale
        //   4.   setup output justification

        formatter.format(sb.toString());
    }
}
Using printf - formatTo Implementation 1/2
// 1. check flags (alternate)
boolean alternate = (flags & FormattableFlags.ALTERNATE)
                          == FormattableFlags.ALTERNATE;
alternate |= (precision >= 0 && precision <= 12);
String stamp = (alternate ? stamp12 : stamp24);

// 2. set precision (cut off length)
if (precision == -1 || stamp.length() <= precision)
  sb.append(stamp);
else
  sb.append(stamp.substring(0, precision - 1)).append(‘*’);

// 3. check locale
if (formatter.locale().equals(Locale.CHINESE))
  sb.reverse();

// 4. setup output justification
...
Using printf - formatTo Implementation 2/2
// 4. setup output justification

int n = sb.length();
if (n < width) {
  boolean left = (flags & FormattableFlags.LEFT_JUSTIFY)
                       == FormattableFlags.LEFT_JUSTIFY;
  for (int i = 0; i < (width - n); i++) {
    if (left) {
      sb.append(‘ ’);
    } else {
      sb.insert(0, ‘ ‘);
    }
  }
}
Using printf - Examples
final Alfa alfa = new Alfa();

System.out.printf(“>%s<%n”, alfa);
// >ABCDEF123456GHIJKL123456<
System.out.printf(“>%#s<%n”, alfa);
// >ABCDEF123456<
System.out.printf(“>%.5s<%n”, alfa);
// >ABCD*<
System.out.printf(“>%.8s<%n”, alfa);
// >ABCDEF1*<
System.out.printf(“>%-25s<%n”, alfa);
// >ABCDEF123456GHIJKL123456 <
System.out.printf(“>%15.10s<%n”, alfa);
// >     ABCDEF123*<
System.out.printf(Locale.CHINESE, “>%15.10s<%n”, alfa);
// >     *321FEDCBA<
Using printf - What for?


 Much more powerfull
 than simple toString
 Unified use of printf
  (even on own objects)
 Usefull in CLI apps
 Again: It’s fun
JSUGA Tech Tips




 !at’s a
folks

Más contenido relacionado

La actualidad más candente

Architecture for Massively Parallel HDL Simulations
Architecture for Massively Parallel HDL Simulations Architecture for Massively Parallel HDL Simulations
Architecture for Massively Parallel HDL Simulations
DVClub
 
Fpga 06-data-types-system-tasks-compiler-directives
Fpga 06-data-types-system-tasks-compiler-directivesFpga 06-data-types-system-tasks-compiler-directives
Fpga 06-data-types-system-tasks-compiler-directives
Malik Tauqir Hasan
 
Client Side Programming with Applet
Client Side Programming with AppletClient Side Programming with Applet
Client Side Programming with Applet
backdoor
 
Design patterns as power of programing
Design patterns as power of programingDesign patterns as power of programing
Design patterns as power of programing
Lukas Lesniewski
 
Old Oracle Versions
Old Oracle VersionsOld Oracle Versions
Old Oracle Versions
Jeffrey Kemp
 

La actualidad más candente (20)

Last train to php 7
Last train to php 7Last train to php 7
Last train to php 7
 
How to write maintainable code without tests
How to write maintainable code without testsHow to write maintainable code without tests
How to write maintainable code without tests
 
Architecture for Massively Parallel HDL Simulations
Architecture for Massively Parallel HDL Simulations Architecture for Massively Parallel HDL Simulations
Architecture for Massively Parallel HDL Simulations
 
O que há de novo no Rails 3 - Ruby on Rails no Mundo Real - 23may2010
O que há de novo no Rails 3 - Ruby on Rails no Mundo Real - 23may2010O que há de novo no Rails 3 - Ruby on Rails no Mundo Real - 23may2010
O que há de novo no Rails 3 - Ruby on Rails no Mundo Real - 23may2010
 
Modern PHP
Modern PHPModern PHP
Modern PHP
 
PHP 5.3
PHP 5.3PHP 5.3
PHP 5.3
 
Fpga 06-data-types-system-tasks-compiler-directives
Fpga 06-data-types-system-tasks-compiler-directivesFpga 06-data-types-system-tasks-compiler-directives
Fpga 06-data-types-system-tasks-compiler-directives
 
soscon2018 - Tracing for fun and profit
soscon2018 - Tracing for fun and profitsoscon2018 - Tracing for fun and profit
soscon2018 - Tracing for fun and profit
 
Flask RESTful Flask HTTPAuth
Flask RESTful Flask HTTPAuthFlask RESTful Flask HTTPAuth
Flask RESTful Flask HTTPAuth
 
エラー時にログに出力する情報と画面に表示する情報を分ける #LaravelTokyo
エラー時にログに出力する情報と画面に表示する情報を分ける #LaravelTokyoエラー時にログに出力する情報と画面に表示する情報を分ける #LaravelTokyo
エラー時にログに出力する情報と画面に表示する情報を分ける #LaravelTokyo
 
Client Side Programming with Applet
Client Side Programming with AppletClient Side Programming with Applet
Client Side Programming with Applet
 
How to fake_properly
How to fake_properlyHow to fake_properly
How to fake_properly
 
C++ for Java Developers (JavaZone 2017)
C++ for Java Developers (JavaZone 2017)C++ for Java Developers (JavaZone 2017)
C++ for Java Developers (JavaZone 2017)
 
Applet
AppletApplet
Applet
 
Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2
 
Laravel 5
Laravel 5Laravel 5
Laravel 5
 
Unlock The Mystery Of PHPUnit (Wave PHP 2018)
Unlock The Mystery Of PHPUnit (Wave PHP 2018)Unlock The Mystery Of PHPUnit (Wave PHP 2018)
Unlock The Mystery Of PHPUnit (Wave PHP 2018)
 
Design patterns as power of programing
Design patterns as power of programingDesign patterns as power of programing
Design patterns as power of programing
 
Applet life cycle
Applet life cycleApplet life cycle
Applet life cycle
 
Old Oracle Versions
Old Oracle VersionsOld Oracle Versions
Old Oracle Versions
 

Destacado (8)

Qué es Delibera
Qué es DeliberaQué es Delibera
Qué es Delibera
 
Unit 1, Chapter 2
Unit 1, Chapter 2Unit 1, Chapter 2
Unit 1, Chapter 2
 
Podcasts
PodcastsPodcasts
Podcasts
 
Trucosdelmovil
TrucosdelmovilTrucosdelmovil
Trucosdelmovil
 
Agua Premium
Agua PremiumAgua Premium
Agua Premium
 
NNUG Certification Presentation
NNUG Certification PresentationNNUG Certification Presentation
NNUG Certification Presentation
 
Qué es Delibera
Qué es DeliberaQué es Delibera
Qué es Delibera
 
Website Fuzziness
Website FuzzinessWebsite Fuzziness
Website Fuzziness
 

Similar a JSUG - Tech Tips1 by Christoph Pickl

symfony on action - WebTech 207
symfony on action - WebTech 207symfony on action - WebTech 207
symfony on action - WebTech 207
patter
 

Similar a JSUG - Tech Tips1 by Christoph Pickl (20)

Java 5 and 6 New Features
Java 5 and 6 New FeaturesJava 5 and 6 New Features
Java 5 and 6 New Features
 
Taking Jenkins Pipeline to the Extreme
Taking Jenkins Pipeline to the ExtremeTaking Jenkins Pipeline to the Extreme
Taking Jenkins Pipeline to the Extreme
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best Practices
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
ES2015 workflows
ES2015 workflowsES2015 workflows
ES2015 workflows
 
Ecmascript 2015 – best of new features()
Ecmascript 2015 – best of new features()Ecmascript 2015 – best of new features()
Ecmascript 2015 – best of new features()
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
Unit Testing from Setup to Deployment
Unit Testing from Setup to DeploymentUnit Testing from Setup to Deployment
Unit Testing from Setup to Deployment
 
symfony on action - WebTech 207
symfony on action - WebTech 207symfony on action - WebTech 207
symfony on action - WebTech 207
 
A few good JavaScript development tools
A few good JavaScript development toolsA few good JavaScript development tools
A few good JavaScript development tools
 
Cappuccino @ JSConf 2009
Cappuccino @ JSConf 2009Cappuccino @ JSConf 2009
Cappuccino @ JSConf 2009
 
On Processors, Compilers and @Configurations
On Processors, Compilers and @ConfigurationsOn Processors, Compilers and @Configurations
On Processors, Compilers and @Configurations
 
All I Need to Know I Learned by Writing My Own Web Framework
All I Need to Know I Learned by Writing My Own Web FrameworkAll I Need to Know I Learned by Writing My Own Web Framework
All I Need to Know I Learned by Writing My Own Web Framework
 
Lean Php Presentation
Lean Php PresentationLean Php Presentation
Lean Php Presentation
 
Java 7 New Features
Java 7 New FeaturesJava 7 New Features
Java 7 New Features
 
JavaScript Core
JavaScript CoreJavaScript Core
JavaScript Core
 
10 Catalyst Tips
10 Catalyst Tips10 Catalyst Tips
10 Catalyst Tips
 
Ch ch-changes cake php2
Ch ch-changes cake php2Ch ch-changes cake php2
Ch ch-changes cake php2
 
Quick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineQuick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmine
 

Más de Christoph Pickl

Más de Christoph Pickl (20)

JSUG - AS3 vs Java by Christoph Pickl
JSUG - AS3 vs Java by Christoph PicklJSUG - AS3 vs Java by Christoph Pickl
JSUG - AS3 vs Java by Christoph Pickl
 
JSUG - Layouting TeX documents with the Memoir class
JSUG - Layouting TeX documents with the Memoir classJSUG - Layouting TeX documents with the Memoir class
JSUG - Layouting TeX documents with the Memoir class
 
JSUG - Cocoon3 Student Project Idea by Reinhard Poetz and Steven Dolg
JSUG - Cocoon3 Student Project Idea by Reinhard Poetz and Steven DolgJSUG - Cocoon3 Student Project Idea by Reinhard Poetz and Steven Dolg
JSUG - Cocoon3 Student Project Idea by Reinhard Poetz and Steven Dolg
 
JSUG - ActionScript 3 vs Java by Christoph Pickl
JSUG - ActionScript 3 vs Java by Christoph PicklJSUG - ActionScript 3 vs Java by Christoph Pickl
JSUG - ActionScript 3 vs Java by Christoph Pickl
 
JSUG - TeX, LaTeX und der Rest by Norbert Preining
JSUG - TeX, LaTeX und der Rest by Norbert PreiningJSUG - TeX, LaTeX und der Rest by Norbert Preining
JSUG - TeX, LaTeX und der Rest by Norbert Preining
 
JSUG - TeX Day by Christoph Pickl
JSUG - TeX Day by Christoph PicklJSUG - TeX Day by Christoph Pickl
JSUG - TeX Day by Christoph Pickl
 
JSUG - The Sound of Shopping by Christoph Pickl
JSUG - The Sound of Shopping by Christoph PicklJSUG - The Sound of Shopping by Christoph Pickl
JSUG - The Sound of Shopping by Christoph Pickl
 
JSUG - Tim aka EPROG2 by Martin Schuerrer
JSUG - Tim aka EPROG2 by Martin SchuerrerJSUG - Tim aka EPROG2 by Martin Schuerrer
JSUG - Tim aka EPROG2 by Martin Schuerrer
 
JSUG - Java Service Enabler by Andreas Hubmer
JSUG - Java Service Enabler by Andreas HubmerJSUG - Java Service Enabler by Andreas Hubmer
JSUG - Java Service Enabler by Andreas Hubmer
 
JSUG - Hoppla by Florian Motlik and Petar Petrov
JSUG - Hoppla by Florian Motlik and Petar PetrovJSUG - Hoppla by Florian Motlik and Petar Petrov
JSUG - Hoppla by Florian Motlik and Petar Petrov
 
JSUG - Google Web Toolkit by Hans Sowa
JSUG - Google Web Toolkit by Hans SowaJSUG - Google Web Toolkit by Hans Sowa
JSUG - Google Web Toolkit by Hans Sowa
 
JSUG - TU Wien Cocoon Project by Andreas Pieber
JSUG - TU Wien Cocoon Project by Andreas PieberJSUG - TU Wien Cocoon Project by Andreas Pieber
JSUG - TU Wien Cocoon Project by Andreas Pieber
 
JSUG - TU Wien Castor Project by Lukas Lang
JSUG - TU Wien Castor Project by Lukas LangJSUG - TU Wien Castor Project by Lukas Lang
JSUG - TU Wien Castor Project by Lukas Lang
 
JSUG - LaTeX Introduction by Christoph Pickl
JSUG - LaTeX Introduction by Christoph PicklJSUG - LaTeX Introduction by Christoph Pickl
JSUG - LaTeX Introduction by Christoph Pickl
 
JSUG - OSGi by Michael Greifeneder
JSUG - OSGi by Michael GreifenederJSUG - OSGi by Michael Greifeneder
JSUG - OSGi by Michael Greifeneder
 
JSUG - Filthy Flex by Christoph Pickl
JSUG - Filthy Flex by Christoph PicklJSUG - Filthy Flex by Christoph Pickl
JSUG - Filthy Flex by Christoph Pickl
 
JSUG - Seam by Florian Motlik
JSUG - Seam by Florian MotlikJSUG - Seam by Florian Motlik
JSUG - Seam by Florian Motlik
 
JSUG - Google Guice by Jan Zarnikov
JSUG - Google Guice by Jan ZarnikovJSUG - Google Guice by Jan Zarnikov
JSUG - Google Guice by Jan Zarnikov
 
JSUG - Java FX by Christoph Pickl
JSUG - Java FX by Christoph PicklJSUG - Java FX by Christoph Pickl
JSUG - Java FX by Christoph Pickl
 
JSUG - Inversion Of Control by Florian Motlik
JSUG - Inversion Of Control by Florian MotlikJSUG - Inversion Of Control by Florian Motlik
JSUG - Inversion Of Control by Florian Motlik
 

Último

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 

JSUG - Tech Tips1 by Christoph Pickl

  • 1. JSUGA Tech Tips Christoph Pickl, 2008-06-16
  • 3. Compiler API  “Compiling with the Java Compiler API”  http://java.sun.com/mailers/techtips/corejava/2007/tt0307.html  Standardized with Java6 (JSR-199)  before com.sun.tools.javac.Main  not standard, public programming interface  Also compiles dependent classes  Two possibilities: simple and advanced  both will be covered in next slides
  • 4. Compiler API - Simple - Roadmap  Create sourcecode (programatically created)  Retrieve JavaCompiler via ToolProvider   Invoke run method  Check return code 0 == successfull   Get class via reflection create instance, invoke  methods, get/set fields, ...
  • 5. Compiler API - Simple - The Source  First of all: Create desired sourcecode  Could be created dynamically  Save it in right location  Be aware of Eclipse’ standard src folder package at.sitsolutions.techtips.s4666; public class Hello { public static void sayHello() { System.out.println(“Hello TechTips!”); } }
  • 6. Compiler API - Simple - Compile it package at.sitsolutions.techtips.s4666; import javax.tools.JavaCompiler; import javax.tools.ToolProvider; public class CompilerApi { public static void main(String[] args) { String path = “src/at/sitsolutions/techtips” + “/s4666/Hello.java”; JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); if(compiler.run(null, null, null, path) == 0) { // do something with fresh compiled class } else { System.err.println(“Ups, something went wrong!”); } } }
  • 7. Compiler API - Simple - Use it  After compiling sourcecode...  ... access class reflectively  ... invoke static method // assume we have compiled our sourcecode successfully String className = “at.sitsolutions.techtips.s4666.Hello”; try { Class<?> c = Class.forName(className); Method m = c.getDeclaredMethod(“sayHello”, new Class[] {}); m.invoke(null, new Object[] {}); // prints “Hello TechTips” } catch(Exception e) { e.printStackTrace(); }
  • 8. Compiler API - Simple - Core Method  The JavaCompiler.run method in detail:  (actually inherited from javax.tools.Tool) int run( ... use null for System.in InputSream in, ... use null for System.out OutputStream out, ... use null for System.err OutputStream err, ... files to compile String... args );
  • 9. Compiler API - Advanced  Benefit of advanced version:  Access to error messages  More options (usefull if developing an IDE)  Additionally involved classes:  DiagnosticCollector, JavaFileObject, StandardJavaFileManager, CompilationTask package at.sitsolutions.techtips.s4666; public class Hello2 { public static void sayHello() { System.out.printnl(“Hello TechTips!”); } }
  • 10. Compiler API - Advanced - Compile it JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); StandardJavaFileManager manager = compiler.getStandardFileManager(diagnostics, Locale.ENGLISH, new ISO_8859_11()); String file=“src/at/sitsolutions/techtips/s4666/Hello2.java”; Iterable<? extends JavaFileObject> compilationUnits = manager.getJavaFileObjects(new String[] {file}); CompilationTask task = compiler.getTask(null, manager, diagnostics, null, null, compilationUnits); if(task.call() == false) { // put error handling in here } manager.close();
  • 11. Compiler API - Advanced - Error Handling // error handling for (Diagnostic d : diagnostics.getDiagnostics()) System.out.printf( “Code: %s%nKind: %s%n” + “Position: %s (%s/%s)%n” + “Source: %s%nMessage: %s%n”, d.getCode(), d.getKind(), d.getPosition(), d.getStartPosition(), d.getEndPosition(), d.getSource(), d.getMessage(null)); } /* Code: compiler.err.cant.resolve.location Kind: ERROR Position: 123 (113/131) Source: srcatsitsolutionstechtipss4666Hello2.java Message: srcatsitsolutionstechtipss4666Hello2.java:5: ↵ cannot find symbol */
  • 12. Compiler API - Advanced - Core Method  JavaCompiler.getTask method in detail: CompilationTask getTask( ... use null for System.err Writer out, JavaFileManager mgr, ... use null for compiler’s standard mgr DiagnosticListener lst, ... somehow mandatory Iterable<String> options, ... options to compiler Iterable<String> classes, ... used for annotation processing Iterable<? extends JavaFileObject> ... files to compile compilationUnits );
  • 13. Compiler API - What for?  Be more dynamic Create classes on-the-fly   Let application gain “experience”  Build your own IDE Provide meaningfull error  messages  Highlight specific error in sourcecode  It’s fun
  • 15. Using printf  “Using printf with Customized Formattable Classes”  http://blogs.sun.com/CoreJavaTechTips/entry/using_printf_with_customized_formattable  Format output available since Java5  well known from C language (%5.2f%n)  Formattable interface  formatTo(Formatter, int, int, int):void  use locales, flags, width, precision  Flags available:  ALTERNATE (#), LEFT_JUSTIFY (-), UPPERCASE (^)  Usage just as known from C language
  • 16. Using printf - The Formattable Object public class Alfa implements Formattable { private final String stamp12 = “ABCDEF123456”; // alternate private final String stamp24 = “ABCDEF123456GHIJKL123456”; // default public void formatTo( Formatter formatter, int flags, int width, int precision) { StringBuilder sb = new StringBuilder(); // 1. check flags (alternate) // 2. set precision (cut off length) // 3. check locale // 4. setup output justification formatter.format(sb.toString()); } }
  • 17. Using printf - formatTo Implementation 1/2 // 1. check flags (alternate) boolean alternate = (flags & FormattableFlags.ALTERNATE) == FormattableFlags.ALTERNATE; alternate |= (precision >= 0 && precision <= 12); String stamp = (alternate ? stamp12 : stamp24); // 2. set precision (cut off length) if (precision == -1 || stamp.length() <= precision) sb.append(stamp); else sb.append(stamp.substring(0, precision - 1)).append(‘*’); // 3. check locale if (formatter.locale().equals(Locale.CHINESE)) sb.reverse(); // 4. setup output justification ...
  • 18. Using printf - formatTo Implementation 2/2 // 4. setup output justification int n = sb.length(); if (n < width) { boolean left = (flags & FormattableFlags.LEFT_JUSTIFY) == FormattableFlags.LEFT_JUSTIFY; for (int i = 0; i < (width - n); i++) { if (left) { sb.append(‘ ’); } else { sb.insert(0, ‘ ‘); } } }
  • 19. Using printf - Examples final Alfa alfa = new Alfa(); System.out.printf(“>%s<%n”, alfa); // >ABCDEF123456GHIJKL123456< System.out.printf(“>%#s<%n”, alfa); // >ABCDEF123456< System.out.printf(“>%.5s<%n”, alfa); // >ABCD*< System.out.printf(“>%.8s<%n”, alfa); // >ABCDEF1*< System.out.printf(“>%-25s<%n”, alfa); // >ABCDEF123456GHIJKL123456 < System.out.printf(“>%15.10s<%n”, alfa); // > ABCDEF123*< System.out.printf(Locale.CHINESE, “>%15.10s<%n”, alfa); // > *321FEDCBA<
  • 20. Using printf - What for?  Much more powerfull than simple toString  Unified use of printf (even on own objects)  Usefull in CLI apps  Again: It’s fun
  • 21. JSUGA Tech Tips !at’s a
  • 22. folks