Personal blog
www.milovetingting.cn
Java based
preface
This article takes notes for learning about Java, refer to the following resources :github.com/Snailclimb/… Thanks for sharing!
JAVA exception classification and processing
concept
If a method does not complete its task in the normal way, it can exit the method through another path. In this case an object is thrown that encapsulates the error message. At this point, the method immediately exits without returning any value. In addition, the rest of the code that calls this method cannot continue to execute, and the exception handling mechanism hands off the code execution to the exception handler
Abnormal classification
Throwable is the superclass for all errors or exceptions in the Java language. The next layer is divided into Error and Exception
Error
The Error class refers to internal errors and resource exhaustion errors of the Java runtime system. The application does not throw such objects. If such an error occurs, all that is left is to inform the user and try to terminate the program safely
Exception (RuntimeException, CheckedException)
Exception has two branches: RuntimeException and CheckedException
RuntimeException For example, NullPointerException and ClassCastException. One is to check for abnormalities such as IOExceptions caused by I/O errors and SQLException. RuntimeException is a superclass of exceptions that might be thrown during normal operation of the Java Virtual machine. If a RuntimeException occurs, it must be the programmer’s fault.
CheckedException: an external error that occurs during compilation. The Java compiler forces your program to try and catch an exception.
-
Attempted to read data at the end of the file
-
Attempted to open a malformed URL
-
An attempt was made to find a class object based on a given string representing a class that does not exist
How to handle exceptions
Throws a problem to the caller (throw,throws).
There are three types of throwing exceptions: throw, throws, and automatic throwing by the system
public static void main(String[] args) {
String s = "abc";
if(s.equals("abc")) {
throw new NumberFormatException();
} else{ System.out.println(s); }}int div(int a,int b) throws Exception{
return a/b;
}
Copy the code
Try catch Specifies the processing method for catching exceptions
Throws and throws
Different location
Throws is used on functions, followed by exception classes, which can be multiple. A throw is used inside a function, followed by an exception object.
Function of different
Throws is used to declare exceptions, so that the caller only knows the possible problems of the function, and can provide the processing method in advance. The throw throws a specific problem object, and by the time the throw is executed, the function is done, jumping to the caller and throwing the specific problem object to the caller. That is, when the throw statement stands alone, do not define other statements below because they cannot be executed.
Throws represents a possibility of exceptions that do not necessarily occur; A throw throws an exception, and executing a throw must throw some kind of exception object.
Both are passive ways of handling exceptions, just throwing or possibly throwing an exception, but not being handled by the function. The actual handling of an exception is handled by the upper level of the function call.
JAVA reflection
Dynamic languages
In a dynamic language, the structure of a program can be changed at runtime: new functions can be introduced, existing functions can be deleted, and other structural changes. For example, JavaScript is a common dynamic language. In addition, Ruby and Python are also dynamic languages, while C and C++ are not dynamic languages. JAVA is a semi-dynamic language in terms of reflection
Reflection mechanism concept (knowing all properties and methods of a class in the health state)
Reflection in Java means that all properties and methods of any class can be known at runtime. And for any object, can call any of its methods; This ability to dynamically retrieve information and invoke object methods becomes the reflection mechanism of the Java language.
Application of reflection
Compile-time type and run-time type
Many objects in Java programs have two types at run time: compile-time type and run-time type. The type at compile time is determined by the type used when declaring the object, and the type at run time is determined by the type actually assigned to the object. Such as:
Person p=new Student();
The compile time type is Person and the run time type is Student
Compile-time types cannot get concrete methods
A program may also receive an external Object passed in at run time that has a compile-time type of Object, but the program has methods that need to call the runtime type of that Object. To solve these problems, programs need to discover real information about objects and classes at run time. However, if compile time cannot predict which classes the object or class belongs to, and the program has to rely on runtime information to discover the true information about the object or class, then reflection must be used
The Java reflection API
The reflection API is used to generate information about classes, interfaces, or objects in the JVM
-
Class: Reflection of the core Class, can get Class attributes, methods, and other information.
-
Field class: a class in the java.lang. reflec package that represents a member variable of the class that can be used to get and set property values in the class.
-
Method class: a class in the java.lang. reflec package that represents a class’s methods, which can be used to get information about a class’s methods or to execute methods.
-
Constructor class: a class in the java.lang. Reflec package that represents the Constructor of a class.
Reflection usage steps (get Class objects, call object methods)
-
Get the Class object of the Class you want to operate on. It is the core of reflection, through which we can call any method of the Class.
-
Calling a method in the Class Class is the use phase of reflection.
-
Use the reflection API to manipulate this information.
Three ways to get a Class object
Call the getClass() method of an object
Person p=new Person();
Class clazz=p.getClass();
Call the class property of a class to get the corresponding class object for that class
Class clazz=Person.class;
Use the forName() static method in the Class Class (safest/best performance)
Class clazz= class.forname (” full path of Class “); (Most commonly used)
Once we have the Class object of the Class we want to manipulate, we can retrieve and view the methods and properties in the Class through the methods in the Class
// Get the Class object of the Person Class
Class clazz=Class.forName("reflection.Person");
// Get all method information for the Person class
Method[] method=clazz.getDeclaredMethods();
for(Method m:method){
System.out.println(m.toString());
}
// Get all member attribute information for the Person class
Field[] field=clazz.getDeclaredFields();
for(Field f:field){
System.out.println(f.toString());
}
// Get all constructor information for the Person class
Constructor[] constructor=clazz.getDeclaredConstructors();
for(Constructor c:constructor){
System.out.println(c.toString());
}
Copy the code
Two ways to create an object
NewInstance () for Class objects
Use the newInstance() method of the Class object to create instances of the corresponding Class, but this method requires that the corresponding Class have a default empty constructor.
Call newInstance() to the Constructor object
Use the Class object to get the specified Constructor object and then call the Constructor’s newInstance() method to create an instance of the corresponding Class of the Class object. This method creates instances by selecting the Constructor
// Get the Class object of the Person Class
Class clazz=Class.forName("reflection.Person");
// Create an object using the.newinstane method
Person p=(Person) clazz.newInstance();
// Get the constructor and create the object
Constructor c=clazz.getDeclaredConstructor(String.class,String.class,int.class);
// Create an object and set its properties
Person p1=(Person) c.newInstance("Bill"."Male".20);
Copy the code
JAVA annotations
concept
Annotations are a way and method provided by Java to associate information and metadata with elements in a metaprogram. An Annatation is an interface that allows a program to use reflection to get an Annotation object for a specified element in the program, and then use that Annotation object to get metadata information from the Annotation.
Four standard meta-annotations
The meta-annotation is responsible for annotating other annotations. Java5.0 defines four standard meta-annotation types that are used to provide annotations for other annotation types.
The scope of the object decorated by @target
@target specifies the range of objects that the Annotation decorates: Annotations can be used for packages, types (classes, interfaces, enumerations, Annotation types), type members (methods, constructors, member variables, enumerated values), method parameters, and local variables (such as loop variables, catch parameters). Target is used in the Annotation type declaration to clarify the target it modifies
@Retention Defines the length of time that is retained
Retention defines the length of time that the Annotation is retained: represents the level at which the Annotation information needs to be retained, and is used to describe the Annotation’s life cycle (i.e., the range in which the described Annotation is valid). The value (RetentionPoicy) is as follows:
CLASS: valid in the CLASS file RUNTIME: valid at RUNTIMECopy the code
@ – javadoc Documented description
Documented indicates that other types of annotations should be considered a public API for the annotated program member and therefore Documented by a tool such as Javadoc.
Inherited indicates that an annotated type is Inherited
An @Inherited meta-annotation is a markup annotation. @Inherited indicates that an annotated type is Inherited. If an annotation type with the @Inherited annotation is applied to a class, the annotation will be applied to a subclass of that class
Annotation processor
Annotations are no more useful than annotations without methods and work to read them. An important part of working with annotations is to create an annotation handler that uses them. Java SE5 extends the reflection mechanism API to help programmers quickly construct custom annotation handlers. Let’s implement an annotation handler
//1. Define annotations
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FruitProvider {
/** Supplier number */
public int id(a) default- 1;
/*** Supplier name */
public String name(a) default"";/*** Supplier address */
public String address(a) default "";
}
//2. Use annotations
public class Apple {
@FruitProvider(id = 1, name = "Shaanxi Hongfuji Group", address = Yan 'an Road, Xi 'an city, Shaanxi Province)
private String appleProvider;
public void setAppleProvider(String appleProvider) {
this.appleProvider = appleProvider;
}
public String getAppleProvider(a) {
returnappleProvider; }}//3. Annotation processor
public class FruitInfoUtil {
public static void getFruitInfo(Class
clazz) {
String strFruitProvicer = "Supplier Information:";
Field[] fields = clazz.getDeclaredFields();// Get processing annotations by reflection
for (Field field : fields) {
if (field.isAnnotationPresent(FruitProvider.class)) {
FruitProvider fruitProvider = (FruitProvider) field.getAnnotation(FruitProvider.class);
// Where the annotation information is processed
strFruitProvicer = Supplier No. : + fruitProvider.id() + "Supplier Name:"
+ fruitProvider.name() + "Supplier address:"+ fruitProvider.address(); System.out.println(strFruitProvicer); }}}}public class FruitRun {
public static void main(String[] args) {
FruitInfoUtil.getFruitInfo(Apple.class);
/*********** The command output is ***************/
// Supplier No. : 1 Supplier name: Shaanxi Hongfuji Group Supplier address: Yan, Xi 'an, Shaanxi Province}}Copy the code
JAVA inner class
Java classes can define not only variables and methods, but also classes, so that classes defined inside a class are called inner classes. According to the way of definition, inner class can be divided into static inner class, member inner class, local inner class and anonymous inner class.
Static inner class
A static class defined inside a class is a static inner class
public class Out {
private static int a;
private int b;
public static class Inner {
public void print(a) { System.out.println(a); }}}Copy the code
-
A static inner class can access all the static variables and methods of an external class, even if they are private.
-
Static inner classes are the same as normal classes in that they can define static variables, methods, constructors, etc.
-
Other classes using static inner classes need to use “outer classes”. Inner Inner =new out.inner (); inner.print();
-
The Java collection class HashMap has a static inner class Entry inside it. An Entry is an abstraction of the elements that a HashMap uses to maintain an Entry array, but the Entry is transparent to the user. Static inner classes can be used for things like this that are closely related to an external class and do not depend on an instance of an external class.
Member inner class
A non-static class defined inside a class is a member inner class. Member inner classes cannot define static methods and variables (except for final modifications). This is because the in-member class is non-static, and the class initializes the static members first. If the in-member class is allowed to define static variables, the order in which the static variables are initialized is ambiguous.
public class Out {
private static int a;
private int b;
public class Inner {
public void print(a) { System.out.println(a); System.out.println(b); }}}Copy the code
Local inner classes (classes defined in methods)
Classes defined in methods are local classes. If a class is only used in a method, consider using a local class.
public class Out {
private static int a;
private int b;
public void test(final int c) {
final int d = 1;
class Inner {
public void print(a) { System.out.println(c); }}}}Copy the code
Anonymous inner classes (to inherit a parent class or implement an interface, use new directly to generate a reference to an object)
Anonymous inner classes we must either inherit from a parent class or implement an interface, or only inherit from a parent class or implement an interface. It also has no class keyword, because anonymous inner classes use new directly to generate a reference to an object
public abstract class Bird {
private String name;
public String getName(a) {
return name;
}
public void setName(String name) {
this.name = name;
}
public abstract int fly(a);
}
public class Test {
public void test(Bird bird){
System.out.println(bird.getName() + "Able to fly" + bird.fly() + "米");
}
public static void main(String[] args) {
Test test = new Test();
test.test(new Bird() {
public int fly(a) {
return 10000;
}
public String getName(a) {
return "Goose"; }}); }}Copy the code
JAVA generics
Generics provide a compile-time type-safety detection mechanism that allows programmers to detect illegal types at compile time. The nature of generics is parameterized typing, which means that the data type being operated on is specified as a parameter. For example, if we want to write a sorting method that can sort arrays of integers, arrays of strings, or any other type of array, we can use Java generics
Generic methods ()
You can write a generic method that accepts different types of arguments when called. The compiler handles each method call appropriately, depending on the type of argument passed to the generic method.
// The generic method printArray
public static < E > void printArray( E[] inputArray )
{
for ( E element : inputArray ){
System.out.printf( "%s ", element ); }}Copy the code
- Indicates that the type represented by the wildcard is a subclass of T.
- Indicates that the type represented by the wildcard is a parent of type T.
A generic class
The declaration of generic classes is similar to that of non-generic classes, except that a type parameter declaration section is added after the class name. As with generic methods, the type parameter declaration section of a generic class contains one or more type parameters separated by commas. A generic parameter, also known as a type variable, is an identifier used to specify the name of a generic type. Because they take one or more arguments, these classes are called parameterized classes or parameterized types.
public class Box<T> {
private T t;
public void add(T t) {
this.t = t;
}
public T get(a) {
returnt; }}Copy the code
Type wildcard?
What are the generic ligands of the class? The class parameter number of surrogate. Cases such as the List <? > List, the parent of all List< concrete type arguments > on logics
Type erasure
Generics in Java are basically implemented at the compiler level. The type information in the generics is not contained in the generated Java bytecode. Type parameters added when using generics are removed by the compiler at compile time. This process is called type erasure. Types such as List and List defined in code become lists when compiled. All the JVM sees is the List, and the type information added by generics is invisible to the JVM. The basic process of type erasure is also relatively simple, starting with finding the concrete class to replace type parameters. This concrete class is usually Object. If an upper bound is specified for a type parameter, this upper bound is used. Replace all the type arguments in your code with concrete classes
JAVA serialization (creating reusable JAVA objects)
Save (persist) objects and their state to memory or disk
The Java platform allows us to create reusable Java objects in memory, but in general these objects are only possible when the JVM is running, that is, they don’t have a lifetime longer than the JVM’s lifetime. In a real-world application, however, you might want to be able to save (persist) the specified object after the JVM stops running and re-read the saved object at a later date. Java object serialization helps us do this.
Serialized objects are held as byte arrays – static members are not saved
With Java object serialization, when an object is saved, its state is saved as a set of bytes that can be assembled into objects in the future. It is important to note that object serialization holds the object’s “state,” its member variables. Thus, object serialization does not care about static variables in a class.
Serialized user remote object transfer
In addition to using object serialization when persisting objects, object serialization is used when using RMI(remote method calls), or when passing objects over a network. The Java serialization API provides a standard mechanism for handling object serialization and is easy to use.
Serializable implements serialization
In Java, a class can be serialized as long as it implements the Java.io.Serializable interface
ObjectOutputStream and ObjectInputStream serialize and deserialize objects
Serialize and deserialize objects with ObjectOutputStream and ObjectInputStream
WriteObject and readObject customize serialization policies
Adding writeObject and readObject methods to the class enables you to customize your serialization strategy
Serialization ID
Whether the virtual machine allows deserialization depends not only on the same classpath and function code, but also on the same serialization ID of the two classes (private Static Final Long serialVersionUID).
Serialization does not hold static variables
Sequence class description of children and parents
To serialize a superclass object, you need to have the superclass implement the Serializable interface as well.
The Transient keyword prevents the variable from being serialized to a file
-
Add the Transient keyword before the variable declaration to prevent the variable from being serialized to the file. After deserialization, the value of the Transient variable is set to its initial value, such as 0 for int and NULL for object.
-
The server to the client sends the serialized object data, some of object data is sensitive, such as password string, etc., hope to the password field when serialization, encrypt, and client if have a decryption key, only when the client deserialize, can read the password, so that we can to a certain extent to ensure that the serialized object data security.
JAVA copy
There are three ways to copy a reference from one object to another. The first method is direct assignment, the second is shallow copy, and the third is deep copy. All three concepts are really about copying objects
Direct assignment copy
Direct assignment. In Java, a1 = a2, we need to understand that this is actually copying A reference, meaning a1 and A2 refer to the same object. Therefore, when A1 changes, the member variables in A2 also change
Shallow copy (copying a reference but not a referenced object)
Create a new object and copy the non-static fields of the current object into the new object, or if the fields are of value type. If the field is a reference type, the reference is copied but not the referenced object. Therefore, the original object and its copy refer to the same object
class Resume implements Cloneable{
public Object clone(a) {
try {
return (Resume)super.clone();
} catch (Exception e) {
e.printStackTrace();
return null; }}}Copy the code
Deep copy (copy objects and their applied objects)
The deep copy not only copies the object itself, but also all objects that the object contains references to
class Student implements Cloneable {
String name;
int age;
Professor p;
Student(String name, int age, Professor p) {
this.name = name;
this.age = age;
this.p = p;
}
public Object clone(a) {
Student o = null;
try {
o = (Student) super.clone();
} catch (CloneNotSupportedException e) {
System.out.println(e.toString());
}
o.p = (Professor) p.clone();
returno; }}Copy the code
Serialization (deep Clone implementation)
In the Java language, it is often possible to make a deep copy of an object implement the Serializable interface, then write the object (which is really just a copy of the object) to a stream, read from the stream, and rebuild the object