Java Snippets

From no name for this wiki
Jump to: navigation, search

Kleine Code Snipptes für Java.

Zentrieren von Text in einem Bild

Benötigte Funktion ist getStringBounds von der Klasse FontMetrics.

 BufferedImage image = createBufferedImage();
 double height = (double) image.getHeight();
 double width = (double) image.getWidth();
 String toCenter = "Hello World";
 Graphics2D g = image.createGraphics();
 
 FontMetrics metrics = g.getFontMetrics();
 Rectancle2D rect = metrics.getStringBounds(toCenter, g);
 double x = width/2.0d - rect.getWidth()/2.0d;
 double y = height/2.0d - rect.getHeight()/2.0d;
 g.drawString((int) x, (int) y,toCenter);

Multidimensionale Arrays

Arrays koennen in Java ugly definiert werden. a1, a2, a3 und a4 sind alles 3-d Arrays vom selben Typ.

    public static void main(String[] args) {
        int[][][] a1 = new int[3][3][3];
        int[][]a2[] = new int[3][3][3];
        int[]a3[][] =  new int[3][3][3];
        int a4[][][] = new int[3][3][3]; 
        a1[0][0][0] = 2;
        a2[0][0][0] = 2;
        a3[0][0][0] = 2;
        a4[0][0][0] = 2;
        System.out.println(a1[0][0][0]);
        System.out.println(a2[0][0][0]);
        System.out.println(a3[0][0][0]);
        System.out.println(a4[0][0][0]);
    }

Druckt 2222

Array Initialization:

Object array = new int[][] {{2,4}, {2}, {1,5,3}};
int[][] casted = (int[][]) array;
		
for(int x=0; x< casted.length; x++){
   for(int y=0; y<casted[x].length; y++){
       int value = casted[x][y];
       System.out.println("x:" + x + " y:" + y + " value:" + value);
   }
}
		
//int notdefined = casted[0][2]; Index out of bounds exception
//System.out.println(notdefined); 

//Here another way to initialize an empty array
int a5[][][] = {{{}}};

printf

Analog zu C's printf. public PrintStream printf(String format, Object... args). Der String format kann folgende Fragmente enthalten: %[argument_index$][flags][width][.precision]conversion. Flags kann folgende Werte aufweisen (nicht abschliessend)

  • f Floating point, dezimale Zahl
  • t Datum
  • x Hexadezimal Integer
  • b Druckt true oder false, je nachdem, ob Input null oder nicht null ist.
  • d ganze Zahl
  • s toString() wird aufgerufen.

Beispiele:

    public static void main(String[] args) {
        System.out.printf("Hello World %b",null); //Prints "Hello World false";
        System.out.printf("Hello %f", 0.3f); //Hello 0.300000
        System.out.printf("Current hour %tH", System.currentTimeMillis()); //Current hour "10" (in my case)
        System.out.printf("%2$d  %3$d",3,4,5); // Prints "4 5"
    }

Calendar

public static void main(String[] args) {
  Calendar calendar = Calendar.getInstance();
  int hourNow = calendar.get(Calendar.HOUR_OF_DAY);
  System.out.println(hourNow);
      
  //Add 12 hours
  calendar.add(Calendar.HOUR, 12);
  int hourIn12H = calendar.get(Calendar.HOUR_OF_DAY);
  System.out.println(hourIn12H);
}

Class in Method

public class Main {
  
    public interface I {public void print();}
    
    public class A {
         public void print(){System.out.println("Class in Class");}
    }
    
    public static void main(String[] args) throws InterruptedException {
        System.out.println(Runtime.getRuntime().availableProcessors());
        class A implements I {
            public void print(){System.out.println("Class in Method");}
        }
        
        I i = new A();
        i.print(); //Prints class in Method
    }      
}

Assertions

Assertions sind defaultmaessig disabled. Mit dem VM argument -ea oder -enableassertions kann man sie einschalten.

  public void xy(int x){
      assert x > 0; //Einfache Form
      assert x > 0 : "Das Argument x muss > 0 sein"; //Komplexere Form
  }

Schlaegt eine Assertion fehl, dann wird ein java.lang.AssertionError geworfen.

Generics, Provider

class A<T> {
    T n;
    
    public A(T obj){
        n = obj;
    }
    public T getObj(){return n;}
    
    public static void aMethod(){
        A<Integer> u = new A("abc");
        u.getObj();
        Integer x = u.getObj();  //This very line will throw a ClassCastException
    }
}

Generics, Client, Key Concepts

Unterschied zu C# siehe jprl

public class Main {

    public static void main(String[] args) {
        List<A> a = new ArrayList<A>();
        List<B> b = new ArrayList<B>();
        List<Object> c = new ArrayList<Object>();
        
        m1(a);
        m2(a); 
        m3(a);
        
       m1(b);
        //m2(b); will not compile
        //m3(b); will not compile
       
        //m1(c); will not compile
        m2(c); 
        //m3(c); will not compile
        
    }    
    private static void m1(List<? extends A> m){}
    private static void m2(List<? super A> m){}
    private static void m3(List<A> m){}
}

class A {}
class B extends A {}

Anbei ein weiteres Beispiel mit einem Interface:

public class Main {

    public static void main(String[] args) {    
        
        List<X> d = new ArrayList<X>();
        List<C> e =  new ArrayList<C>();
        
        m4(d);
        m5(d);
        
        //m4(e); will not compile
        m5(d);
        
    }    
 
     private static void m4(List<X> m){}
     private static void m5(List<? extends X> m){}
}

class A {}
class B extends A {}
class C implements X {}
interface X {}

Weiteres Key-Konzept:

public class Main {

    public static void main(String[] args) {    
        
        List<A> a = new ArrayList<A>();
        List<? extends A> b;
        b = a;
        a.add(new A());
        //b.add(new B()); Will not compile
        b.add(null); //compiles, null allowed
        
    }    
}

class A {}


public class Main {

    public static void main(String[] args) {          
        ArrayList x = new ArrayList();
        m8(x); //Compiles with warning
    }            
    
    public static void m8(ArrayList<String> x){}
   
}

enum

Enum mit Funktionen und Membervariablen:

    enum MyEnum {ABC, DEF ;
        public String info(){return "abc";} 
        public String more(){return "more";}
        int q;
    }

Etwas komplexeres Beispiel:

public class Demo1 {	
	public static void main(String[] args){
		System.out.println(MyEnum.A.info());
		System.out.println(MyEnum.C.info());
	}		
}


enum MyEnum {
	A {String info(){return "A";}},
	B {String info(){return "B";}},
	C;
	String info(){return "default";}
	
}

classpath

Der Classpath kann entweder mit der Option -cp (auch -classpath) bei java und javac angegeben, oder in der Shellvariable CLASSPATH gespeichert werden. Mehrere Eintraege werden mit dem Semicolon getrennt.

java -cp jarx.jar;.;jary.jar

Jar Dateien muessen einzeln angegeben werden, folgendes geht nicht:

java -cp *.jar //Geht nicht!!!

Siehe classpath


Objekte serialisieren und deserialisieren

Serialisieren:

    public static void serialize(Object obj){
        FileOutputStream fos = null;
        try {
            File file = new File("ser.dat");
            fos = new FileOutputStream(file);
            ObjectOutputStream oos = new ObjectOutputStream(fos);       
            oos.writeObject(obj);
        } catch (IOException ex) {
             throw new RuntimeException(ex);
        } finally {
            try {
                fos.close();
            } catch (IOException ex) {
                 throw new RuntimeException(ex);
            }
        }
    }

Deserialisieren:

    public static Object deSerialize() {
        FileInputStream fis = null;
        Object result = null;
        {
            ObjectInputStream ois = null;
            try {
                File file = new File("ser.dat");
                fis = new FileInputStream(file);
                ois = new ObjectInputStream(fis);
                result = (Main) ois.readObject();
                return (Main) result;
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            } catch (ClassNotFoundException ex) {
                 throw new RuntimeException(ex);
            } finally {
                try {
                    ois.close();
                } catch (IOException ex) {
                     throw new RuntimeException(ex);
                }        
            }
        }
    }

Annotation

Definition

package sample;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
	public int intProperty();
	public String stringProperty();
	public String stringProperty2() default "notdefined";
}

Usage:

package sample;

public class AnnotationClient {
	
	@MyAnnotation(intProperty = 3, stringProperty="AString")
	public void myMethod(){}
}

Auswerten:

@MyAnnotation(intProperty=3, stringProperty="myString")
public static  void main(String[] args)   {      
 try {
           Method m = Main.class.getMethod("main", args.getClass());
           MyAnnotation annot =  m.getAnnotation(MyAnnotation.class);
           if(annot == null){
                System.out.println("Annotation not present");
               return;
           }         
           String stringValue = annot.stringProperty();
           System.out.println(stringValue);
        } catch (NoSuchMethodException ex) {
            throw new RuntimeException(ex);
        } catch (SecurityException ex) {
             throw new RuntimeException(ex);
  }
}

Java Primitive

Java Primitives

Instanzieren von Inner classes

Folgendes Beispiel demonstriert Innere Classes

public class Demo1 {	
	public static void main(String[] args){
		A.B b = new A().new B(); //Prints A B
	}		
}


class A {
	public A(){System.out.println("A");}
	class B {
		public B(){System.out.println("B");}		
	}
}