SlideShare a Scribd company logo
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

More Related Content

What's hot

Last train to php 7
Last train to php 7Last train to php 7
Last train to php 7
Damien Seguy
 
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
Juti Noppornpitak
 
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
 
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
Plataformatec
 
PHP 5.3
PHP 5.3PHP 5.3
PHP 5.3
Chris Stone
 
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-directivesMalik Tauqir Hasan
 
soscon2018 - Tracing for fun and profit
soscon2018 - Tracing for fun and profitsoscon2018 - Tracing for fun and profit
soscon2018 - Tracing for fun and profit
hanbeom Park
 
Flask RESTful Flask HTTPAuth
Flask RESTful Flask HTTPAuthFlask RESTful Flask HTTPAuth
Flask RESTful Flask HTTPAuth
Eueung Mulyana
 
エラー時にログに出力する情報と画面に表示する情報を分ける #LaravelTokyo
エラー時にログに出力する情報と画面に表示する情報を分ける #LaravelTokyoエラー時にログに出力する情報と画面に表示する情報を分ける #LaravelTokyo
エラー時にログに出力する情報と画面に表示する情報を分ける #LaravelTokyo
Shohei Okada
 
Client Side Programming with Applet
Client Side Programming with AppletClient Side Programming with Applet
Client Side Programming with Appletbackdoor
 
How to fake_properly
How to fake_properlyHow to fake_properly
How to fake_properly
Rainer Schuettengruber
 
C++ for Java Developers (JavaZone 2017)
C++ for Java Developers (JavaZone 2017)C++ for Java Developers (JavaZone 2017)
C++ for Java Developers (JavaZone 2017)
Patricia Aas
 
Applet
AppletApplet
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
ppd1961
 
Laravel 5
Laravel 5Laravel 5
Laravel 5
Sudip Simkhada
 
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)
ENDelt260
 
Design patterns as power of programing
Design patterns as power of programingDesign patterns as power of programing
Design patterns as power of programingLukas Lesniewski
 
Applet life cycle
Applet life cycleApplet life cycle
Old Oracle Versions
Old Oracle VersionsOld Oracle Versions
Old Oracle VersionsJeffrey Kemp
 

What's hot (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
 

Viewers also liked

Qué es Delibera
Qué es DeliberaQué es Delibera
Qué es Deliberamilcapm
 
Unit 1, Chapter 2
Unit 1, Chapter 2Unit 1, Chapter 2
Unit 1, Chapter 2
Mr. Benson
 
NNUG Certification Presentation
NNUG Certification PresentationNNUG Certification Presentation
NNUG Certification PresentationNiall Merrigan
 
Qué es Delibera
Qué es DeliberaQué es Delibera
Qué es Deliberaguest56d6c8
 
Website Fuzziness
Website FuzzinessWebsite Fuzziness
Website Fuzziness
Niall Merrigan
 

Viewers also liked (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 to JSUG - Tech Tips1 by Christoph Pickl

Taking Jenkins Pipeline to the Extreme
Taking Jenkins Pipeline to the ExtremeTaking Jenkins Pipeline to the Extreme
Taking Jenkins Pipeline to the Extreme
yinonavraham
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
Ganesh Samarthyam
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best Practices
Siarhei Barysiuk
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
ciklum_ods
 
ES2015 workflows
ES2015 workflowsES2015 workflows
ES2015 workflows
Jarrod Overson
 
Ecmascript 2015 – best of new features()
Ecmascript 2015 – best of new features()Ecmascript 2015 – best of new features()
Ecmascript 2015 – best of new features()
Miłosz Sobczak
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
chartjes
 
Unit Testing from Setup to Deployment
Unit Testing from Setup to DeploymentUnit Testing from Setup to Deployment
Unit Testing from Setup to Deployment
Mark Niebergall
 
symfony on action - WebTech 207
symfony on action - WebTech 207symfony on action - WebTech 207
symfony on action - WebTech 207patter
 
A few good JavaScript development tools
A few good JavaScript development toolsA few good JavaScript development tools
A few good JavaScript development tools
Simon Kim
 
Cappuccino @ JSConf 2009
Cappuccino @ JSConf 2009Cappuccino @ JSConf 2009
Cappuccino @ JSConf 2009
tolmasky
 
On Processors, Compilers and @Configurations
On Processors, Compilers and @ConfigurationsOn Processors, Compilers and @Configurations
On Processors, Compilers and @Configurations
Netcetera
 
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
Ben Scofield
 
Lean Php Presentation
Lean Php PresentationLean Php Presentation
Lean Php Presentation
Alan Pinstein
 
10 Catalyst Tips
10 Catalyst Tips10 Catalyst Tips
10 Catalyst Tips
Jay Shirley
 
Ch ch-changes cake php2
Ch ch-changes cake php2Ch ch-changes cake php2
Ch ch-changes cake php2
markstory
 
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
Gil Fink
 

Similar to 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
 

More from Christoph Pickl

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
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
Christoph Pickl
 
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
Christoph Pickl
 
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
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
Christoph Pickl
 
JSUG - TeX Day by Christoph Pickl
JSUG - TeX Day by Christoph PicklJSUG - TeX Day by Christoph Pickl
JSUG - TeX Day by Christoph Pickl
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
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
Christoph Pickl
 
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
Christoph Pickl
 
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
Christoph Pickl
 
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
Christoph Pickl
 
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
Christoph Pickl
 
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
Christoph Pickl
 
JSUG - LaTeX Introduction by Christoph Pickl
JSUG - LaTeX Introduction by Christoph PicklJSUG - LaTeX Introduction by Christoph Pickl
JSUG - LaTeX Introduction by Christoph Pickl
Christoph Pickl
 
JSUG - OSGi by Michael Greifeneder
JSUG - OSGi by Michael GreifenederJSUG - OSGi by Michael Greifeneder
JSUG - OSGi by Michael Greifeneder
Christoph Pickl
 
JSUG - Filthy Flex by Christoph Pickl
JSUG - Filthy Flex by Christoph PicklJSUG - Filthy Flex by Christoph Pickl
JSUG - Filthy Flex by Christoph Pickl
Christoph Pickl
 
JSUG - Seam by Florian Motlik
JSUG - Seam by Florian MotlikJSUG - Seam by Florian Motlik
JSUG - Seam by Florian Motlik
Christoph Pickl
 
JSUG - Google Guice by Jan Zarnikov
JSUG - Google Guice by Jan ZarnikovJSUG - Google Guice by Jan Zarnikov
JSUG - Google Guice by Jan Zarnikov
Christoph Pickl
 
JSUG - Java FX by Christoph Pickl
JSUG - Java FX by Christoph PicklJSUG - Java FX by Christoph Pickl
JSUG - Java FX by Christoph Pickl
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
Christoph Pickl
 

More from 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
 

Recently uploaded

Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 

Recently uploaded (20)

Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 

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