Java Section – Some questions to Master and remember – By Xiaonan
1. The connection and difference between Error and Exception in Java
Error and Exception are subclasses of Throwable
2. Error class generally refers to problems related to virtual machine, such as system crash, virtual machine Error, insufficient memory space, method call stack overflow, etc.
Suggestion: If the application is interrupted and cannot be recovered or prevented by the program itself, the program is recommended to terminate.
The Exception class represents an Exception that a program can handle, catch, and possibly recover.
Suggestion: Handle exceptions as much as possible so that the program can resume running, rather than terminate when an exception occurs.
Both are subclasses of Throwable and are serializable.
Uncheck Exception and Check Exception
1. Uncheck Exception: a defect or logical Error in a program that cannot be recovered at run time and does not need to be thrown syntactically. It includes Error, RuntimeException and its subclasses.
2. Check Exception: invalid external conditions that cannot be directly controlled by the program (such as user input, database problems, network exceptions, and file loss). Try catch processing or throw declaration is required. Includes Error and RuntimeException and their subclasses, as well as other exceptions.
Throws throws
Throw is used inside a method to throw a Throwable exception. If it is a check exception, it must be thrown out and the method caller needs to handle it.
Throws an exception outside the method body. If it is a check exception, the caller must handle it or throw it out (when unable to handle it).
2. Frequently asked knowledge about virtual machines
Basic Features of JVM
1. The JVM is the engine for Java bytecode execution, and it also optimizes Java bytecode into more efficient machine instructions. Programmers write programs that eventually run on the JVM. The JVM shields platform-specific information, enabling Java programs to run unmodified on multiple platforms by generating bytecode files (class files) that run on the JVM. The JVM is responsible for sending each byte code to be executed to the interpreter, which translates it into platform-specific machine instructions and executes it. The most important feature of the Java language is cross-platform running, and the JVM is used to support cross-platform running regardless of the operating system.
2. The loading of classes in the JVM is implemented by the ClassLoader and its subclasses. ClassLoader is an important system component of the Java runtime, responsible for finding stacks and classes that load class files at run time.
Basic functions of DVM
Dalvik mainly performs important functions such as object life cycle management, stack management, process isolation, thread management, security and exception management, and garbage collection. Each Android application corresponds to an independent Dalvik VIRTUAL machine instance at the bottom, and its code is executed under the interpretation of the VIRTUAL machine.
The difference between Android’s DVM and Sun’s standard JVM
1. DVM is register-based while JVM is virtual stack based. Register access speed compared to stack blocks, DVM can achieve maximum optimization based on Android hardware.
DVM executes. Dex files and JVM executes. Class files. The.class files compiled by the Android project and the R.class files generated by the AAPT tool are extracted into a.dex file by the dex tool (which eventually generates apK). Dex files, compared with. Class files, remove redundant information, reduce the number of HARDWARE I/O operations, and improve the class search speed. (In addition, odex file is a further optimization of dex file)
3. All Android threads correspond to Linux threads, so the VIRTUAL machine can rely more on the operating system thread scheduling and management.
4. There is a special virtual machine process called Zygote, which is an incubator for virtual machine instances. It is created when the system is booted up, and it performs initialization of the virtual machine, loading of libraries, prefabrication of libraries, and initialization. If the system needs a new virtual machine instance, it quickly copies itself and provides the fastest data to the system. For some read-only system libraries, all virtual machine instances share a memory area with Zygote.
Garbage collection mechanism for virtual machines
Note: Sun only defines the rules for garbage collection, not its implementation algorithm, and the algorithms used by different virtual machines vary from vendor to vendor.
Commonly used garbage search algorithm:
1. Reference counter algorithm (deprecated after JDK1.1) : by setting a counter for each object, when there is a reference, the counter +1, when the reference is invalid, the counter -1. When the counter reaches zero, the JVM considers the object no longer in use and can be reclaimed. Disadvantages: Does not solve the problem of circular references, and each operation of the counter incurs additional overhead.
Root search: The JVM considers an object to be no longer in use and can recycle it when it is not in GC Root’s reference chain.
GC Root objects include:
Class – Objects that are loaded by the System Class loader. These classes cannot be recycled. They can hold other objects as static fields. It is important to note that classes loaded through user-defined classloaders are not roots unless the corresponding java.lang.Class instance becomes roots in some other way (or more).
Thread – A living Thread
Stack local-java method Local variables or parameters
4. JNI Local – Local variable or parameter of JNI method
5. JNI Global – Global JNI reference
6. Monitor Used – Monitoring objects Used for synchronization
Held by JVM – Objects that are Held by the GC by the JVM for special purposes, but are actually relevant to the JVM’s implementation. Some of the types that might be known are: system classloaders, some important exception classes that the JVM knows about, some pre-allocated objects for handling exceptions, and some custom classloaders. However, the JVM provides no additional information for these objects, so it is left to the analyst to determine which ones are “held by the JVM.”
Garbage collection algorithm for virtual machines:
1. Mark-sweep (the algorithm used by DVM)
Mark-clear algorithm: consists of two phases: “mark” and “clear”. In the marking phase, all objects to be reclaimed are identified and marked. The clear phase follows the mark phase, purging objects that the mark phase determined were not available. The mark-sweep algorithm is a basic collection algorithm. The efficiency of the mark and sweep phase is not high, and the large amount of discontinuous space will be generated after the sweep, so when the program needs to allocate large memory objects, it may not be able to find enough continuous space.
2. Copy algorithm: divide the memory into two equal pieces, use one piece each time, when garbage collection, copy the surviving objects to the other piece, and then clean up the whole memory. The replication algorithm is simple to implement and runs efficiently. However, only half of the replication algorithm can be used at a time, resulting in low memory utilization. The JVM collects the new generation using replication algorithms.
3. Mark-defragment algorithms: move living objects to one end of memory, and then reclaim memory directly beyond the boundary. Memory utilization is improved, and it is suitable for older ages when collection objects have long lifetimes.
4. Generational collection: According to the survival time of objects, the memory is divided into the new generation and the old age, and different recycling algorithms are adopted according to the survival characteristics of objects in each generation. New generation – replication algorithm. Old-time-mark-collation algorithm.
When is the next GC triggered? What is recycled? Can it be triggered manually?
1. When the system is idle.
2. System determines, unpredictable time/when system.gc () is called.
3. Can say the Cenozoic, the old age structure, can say the minor GC /full GC
4. Can describe minor/Full GC trigger condition, OOM trigger condition, reduce the GC tuning policy.
Summary: Programmers have no specific control over timing, and the System calls system.gc () at unpredictable times. You can, of course, use NewRatio to control the ratio of newObject to oldObject, use MaxTenuringThreshold to control the number of times you enter oldObject, Make the oldObject storage space delay to full GC, which causes the timer to trigger a GC time delay of OOM to extend the object lifetime.
To what?
1. Unused objects. 2. Out-of-scope objects/objects whose reference count is empty.
How does gc determine which objects are scoped or not? As for reference counting to determine whether objects are collectable, I can add the following example to let the interviewer analyze whether obj1 and obj2 will be removed by GC.
class C{
public Object x;
}
C obj1,obj2 = new C();
obj1.x = obj2;
obj2.x = obj1;
obj1,obj2 = null;
Copy the code
3. Start gc root to search for unsearchable objects. PS: There are interviewees in this question to supplement the difference between strong citation, weak citation, soft citation, phantom citation, etc., which is not the answer I want to ask, but can be bonus points.
4. The object cannot be searched from root and is still not resurrected after the first mark and cleanup. Analysis: I expect the answer. But it’s really rare for candidates to answer this question, so in my mind I’ll give full marks for # 3.
Summary: Objects that are out of scope or whose reference count is null; Search for unfound objects from GC root, and after a markup, cleanup, there are still no resurrected objects.
What to do?
1. Delete unnecessary objects to free up memory space.
2. Add some instructions such as stopping execution of other threads and running Finalize, etc.
As an aside, one of my most dreaded answers in an interview is “I can’t say, but I can do an Internet search when I do”. Do program development does not to exercise with aniseed “Hui” there are several kinds of writing, not rote learning I agree, I will not remedy the grammar, words, but how much you say the train of thought, to directly answer a Internet search, I couldn’t do obtain can evaluate the candidate’s information, it is hard to continue to explore topics to discuss from the answer. Try to steer your answers to areas you are familiar with and can discuss, and show the interviewer what he or she is best at.
3. Can tell the advantages and disadvantages of copy cleaning, from survivor, to survivor for what the new generation does, tag cleaning for the old generation, whether to clean up after tag cleaning, copy cleaning and tag cleaning, etc.
Summary: Delete unused objects, reclaim memory space; Run the default Finalize, of course the programmer immediately wants to call the dipose call to release resources such as file handles, the JVM uses from survivor, to survivor to tag it clean, object serialization can also resurrect it.
The memory model of the Java virtual machine
The Java virtual machine divides the memory it manages into three logical parts: method area, stack, and heap.
Method areas are statically allocated. The compiler binds variables to a storage location and these bindings do not change at run time.
Constant pools, named constants, String constants, and static variables from source code are stored in the method area.
Java Stack is a logical concept characterized by lifO. The space of a stack may be continuous or discontinuous.
The most typical Stack application is method invocation, where the Java virtual machine creates a method frame each time a method is invoked and exits
The corresponding method frame is popped. The data stored in the stack is also determined at runtime.
Java Heap allocation means a memory management model in which storage space is allocated and reclaimed at run time in an arbitrary order.
The size, amount, and lifetime of data stored in the heap are often undetermined at compile time. Memory for Java objects is always allocated in the heap.
Java memory allocation
1. Base data types are allocated directly in stack space;
2. The method’s formal parameters are allocated directly in the stack space and reclaimed from the stack space after the method call is completed;
3, reference data type, need to use new to create, both stack space allocation of an address space, and heap space allocation of object class variables;
Allocate an address space in the stack space and point to the object area of the heap space. When the method is called, it will be recycled from the stack space.
5. When the local variable new comes out, it is allocated in stack space and heap space. When the life cycle of the local variable ends, the stack space is immediately recycled, and the heap space area is waiting for GC collection.
6. The actual parameters passed in during method call are first allocated in stack space and released from stack space after method call is completed;
String constants are allocated in the DATA section and this is allocated in the heap.
8. Arrays allocate both the name of the array in stack space and the actual size of the array in heap space
3, Java container related issues. [image upload failed…(image-c69bc0-1510450462343)]
Set, List, Map
Set: Realizes the Collection interface, the objects in the Collection are not sorted in a specific way, and there can be no repeated objects.
List: Implements the Collection interface. Objects in the Collection are sorted by index position and can have duplicate objects.
Map: Implements the Map interface. Each element in the collection is a key-value pair. The key can not be repeated, but the value can be repeated.
HashMap and HashTable (array + linked list implementation)
- A HashMap can be almost equivalent to a Hashtable, except that a HashMap is non-synchronized and can accept NULL (a HashMap can accept null keys and values, whereas a Hashtable cannot).
- HashMap is non-synchronized while Hashtable is synchronized, which means that Hashtable is thread-safe and multiple threads can share a Hashtable; Without proper synchronization, multiple threads cannot share a HashMap. Java 5 provides ConcurrentHashMap, which is an alternative to HashTable and is more extensible than HashTable.
- They use different iterations.
Sychronized means that only one thread can change the Hashtable at a time. This means that any thread that updates the Hashtable must acquire the lock first, and any other thread that updates the Hashtable cannot acquire the lock again until the lock is released. HashMap can be synchronized with the following statement: the Map m = Collections synchronizeMap (HashMap); Summary: There are several major differences between Hashtable and HashMap: thread-safety and speed. Use Hashtable only when you need complete thread-safety, and ConcurrentHashMap if you use Java 5 or above.
Difference between ArrayList and Vector
- Vector is thread-safe, that is, thread-synchronized between its methods, whereas ArrayList is line-unsafe.
- Data growth: ArrayList and Vector both have an initial capacity. When the number of elements stored in them exceeds the capacity, the storage space of ArrayList and Vector needs to be increased. Instead of adding one storage unit, the storage space of ArrayList and Vector needs to be increased. The number of additional storage units must be balanced between memory utilization and program efficiency. Vector defaults to double, whereas ArrayList’s growth strategy is not specified in the documentation (1.5 times as seen from the source code). Both ArrayList and Vector can set the initial size of the space. Vector can also set the size of the space to grow. ArrayList provides no method to set the size to grow.
What is the underlying implementation of ArrayList? How to dynamically expand capacity?
1, the bottom is the Object[] array implementation, dynamic capacity expansion is the need to expand the capacity, first new a larger Object[] array, the original array copy over.
When inserting data, check whether the current array length is equal to the size of the ArrayList. If the current array length is equal to the size of the ArrayList, the array is full and you need to create a new array. If the current array length is less than 6, the length of the new array is increased by 12; otherwise, the length of the new array is increased by half. I’m going to insert the new element at the end of the array, size+1,
3. When deleting data, save the deleted data first (for return) to determine whether the subscript is out of bounds. Delete a data, move the following data forward one space, and set the last data to NULL, otherwise a memory leak will occur. Update the size 1.
If size is not 0, set all elements of the array to NULL.
Describes normal collections, synchronous (thread-safe) collections, and concurrent collections in Java
1. Common collections usually have the highest performance, but do not guarantee the safety of multithreading and the reliability of concurrency.
Thread-safe collections simply add synchronized locks to the collection, severely sacrificing performance and making concurrency less efficient
3. Concurrent set (ConcurrentHashMap, ConcurrentLinkedQueue, ConcurrentLinkedDeque) not only ensures the safety of multithreading but also improves the efficiency of concurrency through complex strategies. For example, using the lock segmentation technique avoids locking the entire array for each data operation.
4, strong reference, soft reference, weak reference difference?
Strong references: We use strong references every day when we write code. If an object is strongly referenced by someone, the garbage collector will never collect it. When running out of memory, the Java virtual machine would rather throw outofMemoryErrors to abort the program than randomly recycle objects with strong references to resolve the memory problem.
Soft references: Then if there is enough memory, the garbage collector will not reclaim it, and if there is not enough memory, it will reclaim the memory of these objects. As long as the garbage collector does not collect it, the object can be used by the program. Soft references can be used to implement memory sensitive caching.
Weak references: If an object has only weak references, then the class is unnecessary because the GC will kill the object whenever it is scanned.
Virtual references: Virtual references do not determine the life cycle of an object, unlike other references. If an object holds only virtual references, it can be garbage collected at any time, just as if there were no references at all. Virtual references are mainly used to track the activity of objects being garbage collected.
5. The difference between StringBuilder and StringBuffer
Comparison in execution speed: StringBuilder > StringBuffer
StringBuffer and StringBuilder, they’re String variables, they’re mutable objects, and whenever we use them to manipulate a String, we’re actually operating on an object, rather than creating objects to manipulate like a String, so it’s faster.
StringBuilder: StringBuffer: thread-safe
The JVM cannot guarantee that the StringBuilder operation is safe when used by multiple threads in the StringBuffer, although it is the fastest, but it can guarantee that the StringBuffer will operate correctly. Of course, most of the time we’re doing it in a single thread, so most of the time it’s recommended to use StringBuilder instead of StringBuffer because of the speed.
Summary of the use of the three:
1. If you want to manipulate a small amount of data, use = String
2, Single thread operation string buffer manipulation of large amounts of data = StringBuilder
3, multithreaded manipulation of large amounts of data in the StringBuffer = StringBuffer
Is String a basic data type? Can it be inherited?
String is a reference type, which is implemented using an underlying char array. Because String is final, classes decorated with final in Java cannot be inherited.
So of course strings cannot be inherited.
6. The difference between “Overload” and “Override
Overloading is when different functions use the same function name but have different numbers or types of arguments. Call different functions based on their arguments.
Overwriting (also known as overwriting) is the reimplementation of a virtual function in the base class in a derived class. That is, the function name and parameters are the same, but the implementation body of the function is different.
Hiding is when a function in a derived class hides a function with the same name in the base class.
Overriding and Overloading methods are different manifestations of Java polymorphism. Overriding is a form of polymorphism between superclasses and subclasses, and Overloading is a form of polymorphism within a class.
Override (rewrite)
-
The method name, parameter, and return value are the same.
-
A subclass method cannot narrow the access rights of a parent method.
-
A subclass method cannot throw more exceptions than a parent method (but a subclass method may not).
-
Exists between a parent class and a child class.
-
Methods defined as final cannot be overridden.
They will overload.
-
At least one parameter type, number, or order must be different.
-
You cannot overload a method name that only returns a different value.
-
Exists in parent and subclass, class.
7, hashCode vs. equals:
1. Primitive data types, also known as primitive data types. Byte, short, char, int, long, float, double, Boolean comparison between them, the double equal sign (= =), and compare their values.
== == == == == == = So the result is the same as the double equal sign (==).
Relation to sets:
When putting an object into a collection, we first determine whether the hashcode value of the object to be put into the collection is equal to the hashcode value of any element in the collection. If not, we directly put the object into the collection. If hashCode is equal, then equals determines whether the object is equal to any other object in the collection. If equals determines otherwise, the element is added directly to the collection.
Rules:
1. If two objects are equal according to equals(), then calling the hashCode method of either object must produce the same integer result.
2. If two objects are not equal according to equals(), then calling the hashCode method of either object does not necessarily produce the same integer result. But programmers should be aware that it is possible to improve hash table performance by producing radically different integer results for unequal objects.
3. In general, both methods should be overridden at the same time.
Four ways to create objects in Java bookmark four ways to create objects in Java
1. Create objects with the new statement, which is the most common method of creating objects.
2, by means of reflection, invokes the Java. Lang, Class or Java. Lang. Reflect. The Constructor Class newInstance () instance methods.
Clone () of objects. (The clone call must be marked with Cloneable, default is shallow copy)
4, by means of the deserialization, search invokes the Java. IO. Object ObjectInputStream readObject () method.
[image upload failed…(image-4aaAF2-1510450462343)]
Class loaders and initialization
The class loader type of the JVM
1. What are the types of Java class loaders?
Bootstrap -C++ written, can not see the source code
2, Extension class loader — loading location: jre\lib\ext
3. System (application) classloader (System\App) — loading location: classpath
4, custom loader (must inherit ClassLoader), custom ClassLoader
Can realize bytecode encryption and decryption function
How and when do static variables, static code blocks load?
A: Static variables are created when the class loader loads the class into the JVM, and memory is allocated when static variables are loaded. The code for a static code block is executed only once when the class is first initialized, the first time it is used.
When is the class initialized? (Only the following 6 conditions can cause class initialization of a class.)
1) Create an instance of the class, that is, new an object
2) Access or assign a value to a static variable of a class or interface
3) Call the static method of the class
4) Reflection (class.forname (“com.lyj.load”))
5) Initialize a subclass of a class (initialize the subclass’s parent class first)
6) The startup class indicated by JVM startup, i.e. the class with the same file name and class name
Class initialization steps:
1) If the class is not already loaded and linked, load and link it first
2) If the class has a direct parent, and the class has not been initialized (note: in a classloader, classes can only be initialized once), initialize the immediate parent (not for interfaces).
Add class initializers (such as static variables and static blocks), execute these initializers in turn.
Polymorphic implementation mechanism and implementation method
Implementation mechanism: by the parent class or interface definition of reference variables can point to subclass or specific implementation class instance object, method and procedure calls in the run-time dynamic binding, is a reference to a specific object instance method, which is running in memory method of the object, rather than the type of reference variables defined in the method.
Implementation method (implementation of polymorphism) :
1. Rewrite: the realization of polymorphism between parent class and subclass.
2. Overloading: the implementation of polymorphism in a class.
3. Object transformation
4. Reflection (e.g. in factory mode), etc
11, Java IO
Byte stream and character stream.
1. Byte streams inherit from InputStream and OutputStream.
Character streams inherit from InputStreamReader and OutputStreamWriter.
How to convert byte streams into character streams (Decorator design mode) :
Character input flows through the InputStreamReader implementation. The constructor of this class can pass InputStream objects.
Character output flows through an OutputStreamWriter implementation, whose constructor can be passed to an OutputStream object.
12. Java Multithreading (emphasis)
Two ways to create threads, and the differences?
1. Inherit the java.lang.Thread class.
2. Implement the Runnable interface directly to override the run() method to implement threads.
Similarities: An instance of the java.lang.Thread class is a Thread but it needs to call the Java.lang. Runnable interface to execute, since the Thread class itself is one
Call the Runnable interface.
Difference: Since Java only supports single inheritance, the second method is used to create threads if objects also need to inherit from other classes.
What is the difference between wait and sleep in Java?
The big difference is that while wait releases the lock, sleep holds it all the time. Wait is usually used for interthread interactions, and sleep is usually used to pause execution.
What are the roles of synchronized and volatile?
Volatile essentially tells the JVM that the value of the current variable in the register (working memory) is indeterminate and needs to be read from main memory;
Once a shared variable (a member variable of a class, a static member variable of a class) is volatile, there are two levels of semantics:
1) It ensures visibility when different threads operate on the variable, i.e. one thread changes the value of a variable and the new value is immediately visible to other threads.
2) Forbid instruction reordering.
Synchronized essentially locks the current variable so that only the current thread can access it and other threads are blocked.
Similarities and differences:
1. Volatile can only be used at the variable level; Synchronized can be used at the variable, method, and class levels
2. Volatile only enables change visibility of variables, and does not guarantee atomicity; Synchronized can guarantee the change visibility and atomicity of variables
3. Volatile does not block threads; Synchronized can cause threads to block.
4. Volatile variables are not optimized by the compiler; Variables of the synchronized tag can be optimized by the compiler
What is a thread pool and how is it used?
Thread pool is to put multiple thread objects into a container in advance. When used, it is not necessary to use new threads but directly to get threads from the pool, which saves the time to open up child threads and improves the efficiency of code execution.
In the Java JDK. Util. Concurrent. Executors offers generate multiple thread pool in static methods.
ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(4);
ExecutorService newScheduledThreadPool =Executors.newScheduledThreadPool(4);
ExecutorService newSingleThreadExecutor = Executors.newSingleThreadExecutor();
Describe your understanding of thread pools?
(If asked, expand on how thread pools are used, the benefits of thread pools, and the startup strategy of thread pools.)
There are three benefits to using thread pools properly.
First: reduce resource consumption. Reduce the cost of thread creation and destruction by reusing created threads.
Second: improve response speed. When a task arrives, it can be executed immediately without waiting for the thread to be created.
Third: improve thread manageability. Threads are scarce resources, and if they are created without limit, they consume system resources and degrade system stability
Using thread pools allows for uniform allocation, tuning, and monitoring.
Thread pool startup strategy?
1. When a thread pool is created, there are no threads in it. The task queue is passed in as a parameter. However, even if there are tasks in the queue, the thread pool is also
They will not be implemented immediately.
2. When the execute() method is called to add a task, the thread pool makes the following judgments:
A. If the number of running threads is smaller than corePoolSize, create a thread to run the task immediately;
B. Queue the task if the number of running threads is greater than or equal to corePoolSize.
C. If the queue is full and the number of running threads is smaller than maximumPoolSize, create a thread to run the queue
A task;
D. If the queue is full and the number of running threads is greater than or equal to maximumPoolSize, the thread pool will throw an exception
The caller says, “I can’t take any more assignments.”
3. When a thread completes a task, it takes the next task from the queue and executes it.
4. When a thread has nothing to do for more than a certain keepAliveTime, the thread pool determines that if the number of threads currently running is greater than corePoolSize, the thread is stopped. So after all the tasks in the thread pool are complete, it will eventually shrink to the size of corePoolSize.
How do YOU control the number of concurrent access threads a method allows?
Acquire Semaphore (); acquire Semaphore (); acquire Semaphore (); Semaphore.release (); semaphore.release();
Because the number of semaphores is limited, when the semaphore is 0, the new thread cannot acquire semaphore and waits when accessing the change method.
Three threads A, B, C run concurrently, b, C need to complete the initialization of thread A data how to achieve?
Control by Semaphore: initialize two Semaphore, a thread get all; After thread A finishes initializing data, two semaphores are released to cause thread B and thread C to start executing.
13. Reflection – Function: Implementation framework
Reflection understanding
To sum up: Reflection is the mapping of components of a Java class through Java’s reflection API into corresponding Java classes, which can then be used. Methods, constructors, member variables, types, packages, etc.
Class: The Class used to describe Java classes is Class. Each Class occupies a piece of memory in the Java virtual machine, and the contents are the bytecode (Class) of that Class.
Three ways to get a bytecode Class
Class 2, object. GetClass 3, class.forname (” the full name of the class “) (dynamically loaded, related to reflection)
Agent with AOP
Add system functionality, such as exception handling, logging, runtime of computation methods, transaction management, and so on, to existing methods of multiple target classes that have the same interface (already developed or without source code). You can use proxies, and they have this advantage. The JVM can dynamically generate bytecode for classes at run time, and such dynamically generated classes are often used as proxies, called dynamic proxies. JVM generated classes must implement one or more interfaces, so JVM generated classes act as proxies for target classes with the same family.
The difference between static and dynamic proxies
Static proxies typically represent only one class, while dynamic proxies represent multiple implementation classes under an interface.
Static agents know what to proide in advance, whereas dynamic agents don’t know what to proide until run time.
The dynamic Proxy is the invoke method that implements the JDK’s InvocationHandler interface, but note that the Proxy is the interface, that is, your business class must implement the interface and get the Proxy object via the newProxyInstance in the Proxy.
There is also a dynamic proxy, CGLIB, which is a class that does not need a business class to inherit the interface and implements the proxy through a derived subclass. Classes are modified by dynamically modifying the bytecode at run time.
AOP programming is based on dynamic proxy implementation, such as famous Spring framework, Hibernate framework and so on are dynamic proxy use examples.
AOP: Aspect Oriented programming (AOP is the acronym of Aspect Oriented Program). At run time, the idea of dynamically cutting code into the specified method and location of a class is Aspect Oriented programming. Technically, AOP is basically implemented in a proxy manner.
Implementation: Bytecode generation of the proxy class object requires passing in an InvocationHandler object. The invocation of the proxy class method triggers the distribution of the InvocationHandler (invoke method), and the InvocationHandler internally calls the method of the object of the proxy class. And insert some specified functionality.
14, annotations,
The concept of annotations: Annotations are actually a class, and writing annotations is actually an object that creates annotations. Annotations are the equivalent of marking a program. Javac compilation tools, development tools, and other programs can use reflection to find out if there are any annotations on your classes and various elements (and can get the values on the annotations) and do the corresponding processing. Tags can be added to packages, types (including classes, enumerations, interfaces), fields, methods, method parameters, and local variables.
The life cycle of annotations
- SOURCE: Annotations are reserved for the SOURCE file stage. When Javac compiles the source file to a. Class file, the corresponding annotations are removed. Common Override and SuppressWarnings, for example, fall within the lifecycle of the SOURCE type because the annotations are useless once the code is compiled.
- CLASS: When the Java virtual machine loads bytecode into memory through the CLASS loader, the annotation is removed and therefore cannot be retrieved by reflection.
- RUNTIME: Annotations remain on top of the bytecodes in memory and can still be used by the virtual machine while running bytecodes. For example Deprecated, when a class is being used by someone else, it is loaded into memory, scanned from the binary code to see if it is obsolete, rather than checking the source code.
15 and generic
Generics are used in collections and other areas, eliminating the insecurity of casting, including the code phase and the run phase. Generics are intended for the compiler to intercept illegal input in the source program, and after compilation, the type information will be removed (so you can use reflection to obtain the ADD method and manually call ADD to add non-T type data to the collection) to ensure the efficiency of the program. For parameterized generic types, the getClass method returns exactly the same value as the original type.
16, regular