Java Kompaktübersicht 07.01.2016import static java.lang.Math.*; public class Java { //////////////////////// Static Imports //////////////////////// // siehe obiger import void staticImport() { double r = cos(PI); // Literatur: // [http://java.sun.com/j2se/1.5.0/docs/guide/language/static-import.html] } /////////////////////// Assertions /////////////////////////// void assertions() { int month=0; assert month==0; // kein AssertionError assert month==1:666; // detailierter Assertionerror // D:\>java -enableassertions -cp . java5 // Exception in thread "main" java.lang.AssertionError: 666 // at java5.main(java5.java:6) // Literatur: // The assertion statement has two forms. The first, simpler form is: // assert Expression1 ; // where Expression1 is a boolean expression. When the system runs the assertion, it evaluates Expression1 and if it is false throws an AssertionError with no detail message. // The second form of the assertion statement is: // assert Expression1 : Expression2 ; // where: // Expression1 is a boolean expression. // Expression2 is an expression that has a value. (It cannot be an invocation of a method that is declared void.) // [http://java.sun.com/j2se/1.5.0/docs/guide/language/assert.html] } /////////////////////// Static Initializers /////////////////////////// static { System.out.println("Abarbeitung vor Aufruf main, nach dem Laden der Klasse."); // Literatur: // Any static initializers declared in a class are executed when the class is initialized and, together with any field initializers (§8.3.2) // for class variables, may be used to initialize the class variables of the class // [http://java.sun.com/docs/books/jls/first_edition/html/8.doc.html#39245] } /////////////////////// Inner Classes /////////////////////////// int i; class InnerClass { int i; public InnerClass() { this.i=5; Java.this.i=10; // Zugriff auf i der outer class } } // Literatur: // The Java programming language allows you to define a class within another class. // Such a class is called a nested class and is illustrated here: // Terminology: Nested classes are divided into two categories: static and non-static. // Nested classes that are declared static are simply called static nested classes. // Non-static nested classes are called inner classes. // [http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html] /////////////////////// Anonyme Klasse /////////////////////////// void anonymeKlasse() { System.setSecurityManager(new SecurityManager() { public void checkConnect(String host, int port) { throw new SecurityException(); } }); } // Literatur: // An anonymous class declaration is automatically derived from a class instance creation expression by the compiler. // An anonymous class is never abstract (§8.1.1.1). An anonymous class is always an inner class (§8.1.3); // it is never static (§8.1.1, §8.5.2). An anonymous class is always implicitly final (§8.1.1.2). // [http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.9.5] /////////////////////// enum /////////////////////////// enum MyEnum1 { EINS,ZWEI } enum MyEnum2 { instanz1,instanz2 { public void eineMethode() {System.out.println("Welt");} } ,instanz3,instanz4; public void eineMethode() {System.out.println("Hallo");} } void enums() { MyEnum1 a = MyEnum1.EINS; MyEnum2 b = MyEnum2.instanz1; b.eineMethode(); // -> "Hallo" b = MyEnum2.instanz2; b.eineMethode(); // -> "Welt" } // Literatur: // But appearances can be deceiving. Java programming language enums are far more powerful than their counterparts // in other languages, which are little more than glorified integers. The new enum declaration defines a full-fledged class // (dubbed an enum type). In addition to solving all the problems mentioned above, it allows you to add arbitrary methods // and fields to an enum type, to implement arbitrary interfaces, and more. Enum types provide high-quality implementations // of all the Object methods. They are Comparable and Serializable, and the serial form is designed to withstand arbitrary // changes in the enum type. // [http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html] // The enum class body can include methods and other fields. The compiler automatically // adds some special methods when it creates an enum. For example, they have a static // values method that returns an array containing all of the values of the enum in the // order they are declared. This method is commonly used in combination with the for-each // construct to iterate over the values of an enum type. // [http://java.sun.com/docs/books/tutorial/java/javaOO/enum.html] //////////////////////// erweiterte for -schleife //////////////////////// void forEach() { for(MyEnum2 tmp:MyEnum2.values()) tmp.eineMethode(); // oder int[] ia={0,1}; for(int tmp : ia) System.out.println(tmp); // -> Ausgabe "0\n1\n" } // Literatur: // for ( Typ Bezeicher : Feld ) // [http://www.galileocomputing.de/artikel/gp/artikelID-152] // So when should you use the for-each loop? Any time you can. It really beautifies your code. // Unfortunately, you cannot use it everywhere. Consider, for example, the expurgate method. The program needs access to the // iterator in order to remove the current element. The for-each loop hides the iterator, so you cannot call remove. // Therefore, the for-each loop is not usable for filtering. Similarly it is not usable for loops where you need to // replace elements in a list or array as you traverse it. Finally, it is not usable for loops that must iterate over // multiple collections in parallel. These shortcomings were known by the designers, who made a conscious decision to // go with a clean, simple construct that would cover the great majority of cases. // [http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html] //////////////////////// autoboxing und einfache generics //////////////////////// void generics() { java.util.Vector <Double> v = new java.util.Vector <Double> (); v.add(Math.PI); double u1=v.elementAt(0)*1.0; } // Ein Algorithmus, der von einem Datentyp unabhängig programmiert werden kann, heißt generisch, und die Möglichkeit, // in Java mit generischen Typen zu arbeiten, heißt Generics. [In C(++) werden diese Typen von Klassen parametrisierte // Klassen oder Templates (Schablonen) genannt. ] ... generische Typen können in Java nur Objekte sein,aber keine primitiven // Datentypen. Das schränkt die Möglichkeiten zwar ein, doch weil es Autoboxing gibt, lässt sich damit leben. // [http://www.galileocomputing.de/openbook/javainsel7/javainsel_06_012.htm#mja3b74e78954e86f60acd2f5cf19bd3ed] // Aber: // So when should you use autoboxing and unboxing? Use them only when there is an “impedance mismatch” between reference // types and primitives, for example, when you have to put numerical values into a collection. It is not appropriate // to use autoboxing and unboxing for scientific computing, or other performance-sensitive numerical code. An Integer // is not a substitute for an int; autoboxing and unboxing blur the distinction between primitive types and reference // types, but they do not eliminate it. // [http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html] //////////////////////// Variable Argumentlisten //////////////////////// void vargl() { // Autoboxing wird auch hier genutzt (Performance, intern als Array!) System.out.printf("%d %d", 1, 2); } // Literatur: // ...It is still true that multiple arguments must be passed in an array, // but the varargs feature automates and hides the process... // There is a strong synergy between autoboxing and varargs, ... // [http://java.sun.com/j2se/1.5.0/docs/guide/language/varargs.html] //////////////////////// Schablonen für Klassen und Methoden //////////////////////// class Schablone1 <CompilerGepruefterTypFuerZuweisungenUnterPingPongReferenzen> {} class Schablone2 <T extends java.util.Observer & java.util.List> {} // akzeptiert nur entsprechende Interfaces class ObservingVector extends java.util.Vector implements java.util.Observer { public void update(java.util.Observable o, Object arg) {}} static class Schablone3 {static <T> T compare(T a, T b) { return a.equals(b)?a:null;}} void schablonen() { Schablone1 <String> fuerStrings = new Schablone1 <String> (); // Schablone1 <Double> fuerDoubles = fuerStrings; // [liefert Compilerfehler] Schablone2 <ObservingVector> tmp1 = new Schablone2 <ObservingVector> (); if(Schablone3.compare("aa","b")==null) System.out.println("ungleich"); } // Literatur: // [http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf] //////////////////////// Annotations //////////////////////// @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME) // die eigene annotation verfügbar machen für Reflection @interface EineAnnotationFuerDenZugriffPerReflection { String was();} // die eigene annotation selbst @EineAnnotationFuerDenZugriffPerReflection(was="Methode") static void annotations(@EineAnnotationFuerDenZugriffPerReflection(was="Paramter") int arg) { // die Methode mit annotations für Methode und Paramter try { Class c = new Java().getClass(); java.lang.reflect.Method m = c.getDeclaredMethod("annotations",new Class []{Integer.TYPE}); java.lang.annotation.Annotation[] anMethod = m.getDeclaredAnnotations(); java.lang.annotation.Annotation[][] anParms = m.getParameterAnnotations(); if(anMethod[0] instanceof EineAnnotationFuerDenZugriffPerReflection) System.out.println(((EineAnnotationFuerDenZugriffPerReflection)anMethod[0]).was()); // >Methode if(anParms[0][0] instanceof EineAnnotationFuerDenZugriffPerReflection) System.out.println(anParms[0][0].getClass().getDeclaredMethod("was").invoke(anParms[0][0])); // >Parameter if (m.isAnnotationPresent(EineAnnotationFuerDenZugriffPerReflection.class)) System.out.println(true); } catch(Exception e) {e.printStackTrace();} } // Literatur: // Annotations have a number of uses, among them: // * Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings. // * Compiler-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth. // * Runtime processing — Some annotations are available to be examined at runtime. // Annotations can be applied to a program's declarations of classes, fields, methods, and other program elements. // Annotations Used by the Compiler: @Deprecated,@Override,@SuppressWarnings // [http://java.sun.com/docs/books/tutorial/java/javaOO/annotations.html] // Der Compiler übersetzt die Annotationstypen in Schnittstellen // @Target Was lässt sich annotieren? Klasse, Methode, ...? // @Retention Wo ist die Annotation sichtbar? Nur für den Compiler oder auch für die Laufzeitumgebung? // @Documented Zeigt den Wunsch an, die Annotation in der Dokumentation zu erwähnen. // @Inherited Macht deutlich, dass ein annotiertes Element auch in der Unterklasse annotiert ist. // [http://www.galileocomputing.de/openbook/javainsel7/javainsel_23_007.htm#mjdfe3a073ffa3537630adaaffcb48683d] //////////////////////// Lambdaausdrücke //////////////////////// interface EventHandler { boolean handleEvent( int eventId, int eventSource ); } void addEventHandler(EventHandler handler) { /* ... */ } void useLambdaFunctionalInterface() { this.addEventHandler( (id, src) -> { System.out.println("event: "+id+", "+src); return true; } ); this.addEventHandler( (id, src) -> src > -1 ); } boolean handle(int id, int src) { System.out.println("event: "+id+", "+src); return true; } public void useLambdaMethodReference() { this.addEventHandler( this::handle ); } /* noch ein Hinweis zu Strings: String a="a"; String b=a+""; System.out.println(a+" "+b+" "+(a==b)+" "+a.equals(b)); //>a a false true */ }