Architecture of so-ware systems Lecture 13: Class/object ini<aliza<on, class loaders, reflec<on, data structures David Šišlák david.sislak@fel.cvut.cz
Java virtual machine start-up» create ini<al class» must be present in bootstrap class loader» links the ini<al class» cause loading, linking and invoca<on of other classes» ini<alize class (class vs. instance ini<aliza<on!)» start execu<ng public void main (String[]) 2
Loading and Linking» Loading» finding binary form of class or interface (e.g. compu<ng on the fly)» form Class» implemented by ClassLoader» can cache binary representa<ons (can decrypt, verify dig. signature)» prefetch them based on expected usage» load group of related classes together» Linking» binary form into run-<me state in JVM» verifica<on structural check (correct opcodes, branches, )» prepara<on» create sta<c fields, fill default values (no ini<alizers!)» precompute addi<onal data structures (e.g. method table)» resolu<on of symbolic references valida<on, direct reference 3
Class ini9aliza9on» class is being ini9alized in the following cases:» instance of class has to be created» sta<c method of class is invoked» non-constant sta<c field of class is used» sub-class is ini<alized» invoca<on of reflec<ve methods over class» it is ini<al class for start-up» class is not ini9alized» when sta<c final field is ini<alized with compile-<me constant» class ini9aliza9on sequence» super class ini<aliza<on» ini<aliza<on in declara<on order (you cannot use values a-er, compiled into "<clinit>:()v") :» user class sta<c ini<alizers» ini<alizers sta<c fields (class + interfaces by default public sta<c final) 4
Class ini9aliza9on vs. Class instance ini9aliza9on» requires careful synchroniza<on (synchronized on class object)» Class object state» verified and prepared» being ini<alized by some thread» fully ini<alized and ready for use» in error state verifica<on failed, ini<aliza<on failed (throws NoClassDefFoundError)» Class instance ini<aliza<on» memory alloca<on (fields in class + superclasses) -> OutOfMemoryError» all variables are set to default values (0, false, null)» prepare args for other/super constructor invoca<on (follow this( ) and follow super( ))» execute instance ini<alizers + field ini<alizers in declara<on order (compiled into "<init>:()v )» execute the rest of the body of constructor 5
Ini9alizer block» what is the output?? 7
Ini9alizer block» what is the output? 2 3 1 8
Ini9alizer block - alterna9ve» what is the output?? 9
Ini9alizer block - alterna9ve» what is the output? 2 1 10
Ini9alizer block sta9c variant 11
Ini9alizer block sta9c example» what is the output?? 12
Ini9alizer block sta9c example» what is the output?» throws NullPointerExcep<on due to recursive class ini<aliza<on, and auto-unboxing» correct: 24/05/17 A4B77ASS Course 2 13
Classloader» classloader types:» bootstrap class loader» system class loader searches run<me, inst. extension, class path» user-defined class loader» extrac<on from encrypted file, verify digital signature» loading from non-standard sources (e.g. network)» generate on the fly» each class has» defining class loader finally define Class» ini<a<ng class loader ini<ate class loading (e.g. through other CL)» class is uniquely iden<fied by pair!» fully qualified name» defining class loader 14
Classloader» referenced classes from X are loaded by its defining CL» each class is loaded only once if it is not previously unloaded» method Class loadclass(string) - qualified name» a cache implemented by Class findloadedclass(string)» get raw bytes from class from somewhere» if ok, define class from array of bytes using Class defineclass( )» if failed, delegate loading to other class loader» e.g. Class findsystemclass(string)» e.g. getparent().loadclass(string) CL which creates the current one» if s<ll no class, throw ClassNotFoundExcep9on» if resolve is required call void resolveclass(class) to link class» Class Class.forName(String), Class.getSystemClassLoader().loadClass(String)» cl.loadclass(string), c.newinstance(), constructor.newinstance( ) 15
Reflec9on» can examine or modify the run-<me behavior» create external classes by qualified name (through Class loaders) do not need to have class during compila<on» class browser enumerate members» debugger examine private members» BUT» performance overhead dynamic resolu<on, slower» security restric<ons security context, e.g. Applet» unexpected side-effects access private fields and methods 16
Reflec9on» retrieve Class object» Class getclass() returns instance Class representa<on» XXX.class from type, no instance» e.g. aa.class» Class Class.forName(String), CL.loadClass(String)» Class.getSuperClass(), Class.getClasses(), Class.getDeclaredClasses(), Class.getEnclosingClass(), {Field Method Constructor}.getDeclaringClass()» examine class modifiers and types» Class.getModifiers()» Class.getTypeParameters() get Generic types» Class.getGenericInterfaces()» Class.getSuperclass()» Class.getAnnota9ons() 17
Reflec9on» discovering class members 18
Reflec9on» Fields» get field types, generic types» get field modifiers» get and set field value (private if no security manager)» Methods» get method types including apributes» get method modifiers» invoke method» Constructors» find constructor with specific parameters» get constructor modifiers» create new class instance» Arrays (through java.lang.reflect.array)» get array types» create new array» get/set array components 19
Reflec9on» Method call example: Class<T> c = Class.forName("MyClass"); // Class<T> c = MyClass.class; Method m = c.getmethod( mymethod ); Object retval = m.invoke(object, );» Field usage example: Class<T> c = MyClass.class; Field f = c.getfield( myfield ); Object value = f.get(object); 20
Data structures» primi<ves: boolean(1), byte(1), char(2), int(4), long(8), float(4), double(8)» without implicit alloca<on» placed in frame in variables or operand stack» objects (object header structure overhead)» every object is descendant of Object by default» methods clone(), equals, getclass(), hashcode(), wait( ), no<fy ( ), finalize()» objects for primi<ves: Boolean, Byte, Character, Integer, Long, Float, Double; can be null; all are immutable objects (final values)» other objects» arrays» special data structure which store a number of items of the same type in linear order; have the defined limit» JAVA automa<cally check limita<ons» allocated on the heap» mul<-dimensional arrays = arrays of arrays; ragged array 21
Autoboxing, Unboxing» automa<c conversion from primi<ve to object representa<on and vice versa» since JAVA 5» for example» autoboxing for Integer is based on valueof(int) and intvalue() methods? 23
Autoboxing, Unboxing» automa<c conversion from primi<ve to object representa<on and vice versa» since JAVA 5» for example» autoboxing for Integer is based on valueof(int) and intvalue() methods» works only during assignment or parameter passing? 24
Autoboxing, Unboxing» automa<c conversion from primi<ve to object representa<on and vice versa» since JAVA 5» for example» autoboxing for Integer is based on valueof(int) and intvalue() methods» works only during assignment or parameter passing» example: count word frequency/histogram» boxing and un-boxing brings inefficiencies! 25
Example» what is the output? and what is the output for i=2000 and j=2000?? 26
Example» what is the output? and what is the output for i=2000 and j=2000? true true true true false true» but not a-er serializa<on, there is no readresolve! A4B77ASS Lecture 13 24/05/17 27
Integer usage of iden9ty seman9cs» similar concept as in mul<ton; Integer itself is Immutable (final) 28
Integer 29
Widening vs. autoboxing» what are the outputs?? 30
Widening vs. autoboxing» what are the outputs? long Integer» why? prefer widening cannot use autoboxing before autoboxing to widen primi<ves -> error if no hello(integer) method 31
Example» what is the outputs?? 32
Example» what is the outputs? 100 - because we are removing Integers instead of Short!!» correct: 33
Method overloading» method is iden<fied by its signature» can be compiled and what is the output?? 34
Method overloading» method is iden<fied by its signature» can be compiled and what is the output? YES no ambiguity method with parameter type String» due to JLS specifica<on: The Java programming language uses the rule that the most specific method is chosen. 35
Method overloading» can be compiled and what is the output?? 36
Method overloading» can be compiled and what is the output?» NO cannot find most specific, both are sub-classes of Object but not in the same inheritance hierarchy 37
Method overloading» can be compiled and what is the output?? 38
Method overloading» can be compiled and what is the output? YES method with param types String, Object 39
Method overloading» BUT» this cannot be compiled cannot iden<fy most specific 40
Method overloading» can be compiled and what is the output?? 41
Method overloading» can be compiled and what is the output? YES Collec9on - compile <me resolu<on not run-<me type 42