Java Technology Finishing (4) - Java Basics

1. Java exception classification and handling

Exception handling is to solve the problem that an error occurs during program processing and cannot exit.

(1) Abnormal classification

Object - Throwable (superclass for all errors or exceptions)

  • Error: refers to the internal error and resource exhaustion error of the Java runtime system. The application will not throw this object. If such an error occurs, try to ensure that the system ends safely
  • Exception: Java exceptions have two types of exceptions, runtime exceptions and checked exceptions
    • RuntimeException: For example, NullPointerException and ClassCastException are basically exceptions caused by unreasonable design by programmers
    • CheckedException: For example, IOException and SQLException are generally external errors. This kind of exception occurs in the compilation stage. The Java compiler will force the program to catch the exception, that is, it will ask you to try...catch... this section of the program that may have an exception. Class exceptions generally include several aspects:
      • Attempt to read data at the end of the file
      • An attempt was made to open a malformed URL
      • Attempts to find a class object based on the given string, and the class represented by this string does not exist

(2) Exception handling method

There are three forms of naturally throwing exceptions: throw, throws, and the system automatically throws exceptions

Catch exceptions and handle them with try...catch... as the structure of catching exceptions and processing codes

(3) The difference between throw and throws

  • The location is different: throws is used in the function declaration, and what is thrown is an exception class, and multiple throws can be thrown; throw is used in a function to throw an exception object
  • The functions are different:
    • throws is used to declare exceptions, let the caller understand the possible problems of this function, and give the processing method in advance; throw throws a specific problem object, execute to throw, the program ends immediately, jumps back to the caller, and the specific problem The object throws the caller, that is, when the throw statement exists independently, subsequent programs cannot be executed.
    • Throws indicates the possibility of an exception, and does not necessarily mean that an exception will occur; throw will definitely throw a definite exception

2. Java reflection

(1) Dynamic language: It means that the structure of the program can be changed when it is running, that is, new functions can be introduced, existing functions can be deleted and other structural changes.
(2) The concept of the reflection mechanism: The reflection mechanism in Java is in the running state . For any class, all the properties and methods of this class can be obtained, and for any object, any method of it can be called.
(3) Application of reflection: compile-time type and runtime type

  • Compile-time type: It is determined by the practical type when declaring the object, and the specific method cannot be obtained. For example Person person = new Student();, the type of Person is declared, but it is of type Student at runtime
  • Runtime type: determined by the type of the assignment object

When the program is running, it may receive an object passed in from the outside. The type of the object is Object at compile time, but the program call needs to know the runtime type of the object, so reflection can be used to obtain the type and class information of the object.

(4) Reflection API

The reflection API is used to generate information about classes, interfaces or objects in the JVM.

  • Class class: the core class of reflection, which can obtain information such as attributes and methods of the class.
  • Field class: The class in the java.lang.reflec package, which represents the member variable of the class, used to get and set the attribute value in the class
  • Method class: The class in the java.lang.reflec package, which represents the method of the class, used to obtain method information or call the method in the class
  • Constructor class: The class in the java.lang.reflec package, which represents the construction method of the class

(5) Steps of reflection

  • Get the Class object you want to operate
  • Call the method in the Class class
  • Use the reflection API to manipulate this information

(6) The method of obtaining the Class object

  • Instance object.getClass(): It is the method for the instance object to obtain the Class object
  • Class name.class: When each class is loaded, it will maintain a class attribute, which stores the relevant information of the class
  • Class.forName(): The Class class provides a static method for obtaining Class objects based on the full path

(7) The method of creating a Class object

  • newInstence(): This creation method requires the Class object to have a default empty constructor
  • Constructor's newInstance(): This creation method requires the Constructor to be obtained first, because it is necessary to confirm that the Class object has a constructor

3. Java annotations

(1) Concept: Annotation is a way and method provided by Java to associate information and metadata (metadata) in metaprograms; it is an interface, and the program can obtain the Annotation object in the specified program through reflection, through Annotation object to get metadata information.
(2) Meta-annotation: The role of meta-annotation is to annotate other annotations. JDK 5 defines four standard meta-annotation types.

  • @Target: Describes the scope of the modified object
    • packages
    • Types: class, interface, enumeration, Annotation type
    • Type members: methods, constructors, member variables, enumeration values
    • method parameters
    • Local variables: such as loop variables, catch parameters
  • @Retention: Define the life cycle of Annotation
    • @SOURSE: Valid in source files
    • @CLASS: Valid in class files
    • @RUNTIME: valid at runtime
  • @Documented: Description-javadoc, used to describe other types of annotations should be used as the public API of the marked program members
  • @Inherited: Describes that a marked type is inherited. If the annotation is on a class, the subclass of this class will also inherit the annotations owned by the parent class

(3) Annotation processor

The annotation processor is the core program for reading and using annotations.

Implement an annotation processor:

//1、创建注解处理器
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FruitProvider {
    
    
	public int id() default -1;
	public String name() default "";
	public String address default "";
}

//2、使用注解处理器
public class Apple{
    
    
	@FruitProvider(id=1,name="陕西红富士集团",address="陕西省西安市延安路")
	private String appleProvider;

	public void setAppleProvider(String appleProvider){
    
    
		this.appleProvider = appleProvider;
	}

	public String getAppleProviderO (
		return appleProvider;
	}
}

//3、注解处理器
public class FruitInfoUtil {
    
    
	public static void getFruitInfo(Class<?> clazz) {
    
    
		String strFruitProvicer = "供应商信息:";
		Field[] fields = clazz.getDeclaredFields(); //获取成员变量
		for (Field field : fields){
    
    
			FruitProvider fruitProvider = (FruitProvider) field.getAnnotation(FruitProvider.class);
			strFruitProvicer = "供应商编号:" + fruitProvider.id() + "供应商名称:" + fruitProvider.name() + "供应商地址:" +  fruitProvider.address();
			System.out.println(strFruitProvicer);
		}
	}
}


4. Java inner class

In a Java class, not only variables and methods can be defined, but also classes can be defined. Classes defined inside a class are called inner classes. According to different definition methods, inner classes are divided into static inner classes, member inner classes, local inner classes, and anonymous inner classes. Four kinds.

  • Static inner class: An inner class decorated with the static keyword. This inner class can share all static resources with the outer class, and the 外部类名.内部类名compile-time type can be obtained by using it. For example, there is a static inner class Entry inside the HashMap class.
  • Member inner class: ordinary inner class, this class cannot define static methods and variables (because only static resources belong to class objects, and JVM loads static resources first, which is prone to conflicts)
  • Local inner class: A class defined inside a method that acts as a temporary object for storage.
  • Anonymous inner class: An anonymous inner class must inherit a parent class or only implement an interface, and there is no class keyword, and a reference to an object is directly generated through the new keyword.

5. Generics

Generics are used to declare object types that cannot be determined, and the compiler will determine the object type through the passed in value.

(1) Generic method <E>

public static <E> void printArray(E[] inputArray){
    
    
	for(E element : inputArray) {
    
    
		System.out.printf("%s", element);
	}
}
  • <? extends T>: Indicates that the wildcard represents all subclasses of T
  • <? super T>: Indicates that the wildcard represents all parent classes of T

(2) Generic class <T>

public class Box<T>{
    
    
	private T t;
	
	public void add(T t){
    
    
		this.t = t;
	}
	
	public T get(){
    
    
		return t;
	}
}

(3) Type wildcard <?>

Type wildcards are commonly used with ? Instead of specific type parameters, for example, List<?> is logically the parent class of all List with generic constraints

(4) Type erasure

Generics in Java are basically implemented at the compiler level. Generics do not exist in the generated bytecode. When compiling, the incoming data type is automatically overwritten to the position where the generics are used, so that The process is called type erasure.


6. Serialization

(1) The role of serialization: serialization operations can persist objects and their states to memory or disk
(2) Serialized storage: serialization is to convert incoming objects into byte arrays for storage, but serialization only Focus on its member variables, not on static resources
(3) Serialization usage scenarios: persistent objects; network transfer objects, etc...
(4) Serialization implementation:

  • Java provides java.io.Serializablean interface, as long as the class implements the interface, it can be serialized
  • Serialization and deserialization using ObjectOutputStream and ObjectInputStream
  • Using writeObject and readObject to implement a custom serialization strategy

(5) The key point of deserialization - serialization ID:

  • Serialization ID: Whether the virtual machine supports deserialization depends not only on whether the classpath and function code are consistent, but also on whether the serialization IDs of the two classes are consistent

(6) The use of serialization in the sub-parent class: If the sub-class implements serialization and wants the parent class to be able to serialize, then the parent class must also implement the Serializable interface
(7) Prevent a variable from being serialized: Java provides the Transient keyword to declare that the variable does not participate in the serialization process, and the corresponding transient variable is initialized during deserialization.


7. Java Copy

If you want to copy an object to another object in a Java program, there are three methods: direct assignment, shallow copy, and deep copy.

  • Direct assignment: Directly refer to the same object. On the surface, it is indeed a copy of an object, but it is still the same memory space internally.
  • Shallow copy: Create a new object and copy non-static fields to the new object, but if there is a reference object in the old object, the address of the reference object is copied, that is, the reference object variable directly assigned to the new object.
  • Deep copy: Create a new object, package all the resources of the old object, create a copy and provide it to the new object, that is, two objects with the same structure but different storage addresses. (The implementation can create objects through serialization and deserialization operations)

Guess you like

Origin blog.csdn.net/Zain_horse/article/details/132165257