09 August 2005

繼續...

Varargs

  • Limitation:
    //below are compile error
    public void varargsMustBeLastArguments(String... strings, String illegal) ; 
    public void onlyOneVarargs(String... strings, String... illegals) ; 
    
  • Compiler treat varargs as Array, and allow zero length:
    //declare:
    public void variableStrings(String... strings) ;
    
    //invoking:
    variableStrings();  //zero length is valid;
    variableStrings(new String[] {"A","B"}) ; //pass array
    

Annontation

  • 3 policy of @Retention annotation: SOURCE, CLASS (default), RUNTIME
  • Annotation type is just interface, no implementation at all. The implementation for custom annotation type is almost done via reflection. Thus, for most case we need to apply: @Retention(RetentionPolicy.RUNTIME) to ensure reflection working at runtime. Hibernate Annotation use RUNTIME too.
  • some odd syntax:
    public @interface AnnotationX {   // declare annotation type
        String foo() default "bar" ;  // default value
    }
    
  • default annotation type: @Deprecated, @Override, @SuppressWarnings
  • meta-annotation type: @Target, @Retention, @Documented, @Inherited
  • Subclass only inherit class-level annotation, not method-level.

foreach loop

  • foreach loop can apply to non-generic Iterable, but only for Object
      List list = new ArrayList() ; // non-generic Iterable
      for(Object o: list) { // Object only
         //....
      }
    
  • eclipse built in code template: type "foreach" and press alt+/
  • Authough new foreach is good, we still use old format when we need Iterator. In Eclipse, we can add new code template for Generaric Iterator: Select Menu -> Window -> Java -> Editor -> Templates -> New... and add following template:
    for (Iterator<${iterable_type}> ${iterator} = ${collection}.iterator(); ${iterator}.hasNext(); ) {
    	${iterable_type} ${element} = ${iterator}.next();
    	${cursor}
    }
    
    ( I don't understand why Eclipse 3.1 not built in this template... )

Static import

  • local variable first:
    import static java.lang.System.out;
    public class Test {
        public void shadow(PrintStream out) {        
            out.println("xyz") ; //local variable first
        }
    }
    

Formatter

  • formatter for date:
    //format as -- 2004/01/02 23:10:59
    System.out.printf("%tY/%<tm/%<td %<tk:%<tM:%<tS", System.currentTimeMillis());
    
    //format as -- 20040102 231059
    System.out.printf("%tY%<tm%<td %<tk%<tM%<tS", System.currentTimeMillis());
    
    //format as -- 2004/01/02 
    System.out.printf("%tY/%<tm/%<td", System.currentTimeMillis());
    

Annotation 還真難...


回響

可以用 Tag <I>、<B>,程式碼請用 <PRE>