Serialize and deserialize
- All are to complete the operation of Java objects, write the Java objects to the file of the local hard disk, and restore the Java objects stored in the local file to the Java memory;
- Serialization refers to outputting objects in memory to the hard disk for storage, while deserialization is the opposite operation, reading data from a file and restoring it to data in memory;
How to use serialization
Implement the interface java.io.Serializable for the class, and the object of this class has the function of serialization;
package com.wei.demo1; import java.io.Serializable; public class User implements Serializable { private Integer id; private String name; private Integer age; public User(Integer id, String name, Integer age) { this.id = id; this.name = name; this.age = age; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } }
Node Streams (directly connect files), Processing Streams (must be based on Node Streams)
package com.wei.demo1; import java.io.*; public class Test { public static void main(String[] args) throws Exception { //create object User user = new User(1,"Zhang San",22); //start serialization OutputStream outputStream = new FileOutputStream("D:\\javahome\\test.txt"); ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream); objectOutputStream.writeObject(user); objectOutputStream.flush(); objectOutputStream.close(); outputStream.close(); } }
Persistence: save data permanently;
deserialize
Read data from a file and restore it to a Java object;
package com.wei.demo1; import java.io.*; public class Test2 { public static void main(String[] args) throws Exception { InputStream inputStream = new FileInputStream("D:\\javahome\\test.txt"); ObjectInputStream objectInputStream = new ObjectInputStream(inputStream); User user = (User) objectInputStream.readObject(); System.out.println(user); objectInputStream.close(); inputStream.close(); } }
reflection
- Difficult to understand, very abstract, very important;
- At this stage, you only need to understand the basic concepts of reflection, based on the application;
- Spring framework stage requires in-depth understanding
what is reflection
- Under normal circumstances, instantiated objects are created through classes. Reflection is to reverse this process and obtain object class information by instantiating objects;
- Through reflection, we obtain the structure of the class during the running of the program to complete some specific functions;
Class
- The Class class is the basis of reflection. In Java, an object is used to describe the information of a certain class;
- The Class class is specialized to describe other classes. The instantiated object of each Class class has information corresponding to a certain class;
- There are 3 ways to create a Class object:
- By calling the Class static method forName(String className);
- Created by the target class;
- Created from an object of the target class
package com.wei.demo1; public class Test3 { public static void main(String[] args) throws Exception { //The target class is User, get its information, and get the Class object corresponding to User //full class name, fully qualified class name (class name with package name com.wei.demo1.User) Class clazz1 = Class.forName("com.southwind.demo1.User"); System.out.println(clazz1); //Here class is a class literal Class clazz2 = User.class; System.out.println(clazz2); User user = new User(1,"Zhang San",22); Class clazz3 = user.getClass(); System.out.println(clazz3); System.out.println(clazz1 == clazz2); System.out.println(clazz2 == clazz3); } }
The purpose of obtaining Class is to call its methods to obtain various information of the target class;
method | describe |
---|---|
boolean isInterface() | Determine if the class is an interface |
boolean isArray() | Determine if the class is an array |
boolean isAnnotation() | Determine if the class is an annotation |
String getName() | Get the fully qualified class name of the class |
ClassLoader getClassLoader() | get classloader |
Class getSuperclass() | get parent class |
Package getPackage() | Get the package the class is in |
Package geyPackage() | Get the package the class is in |
Class getInterfaces() | Get the interface implemented by the class |
Field[] getFields() | Get all member variables of a class |
Method[] getMethods() | Get all methods in a class |
Method getMethod(String name,Class... args) | Get the method specified in the class |
Constructor[] getConstructors() | get all constructors |
Constructor getConstructor(Class... args) | Get the specified constructor |
package com.wei.demo1; import java,lang,reflect.Constructor; import java.lang.reflect.Field; public class Test4{ public static void main(String args[]) throws Exception{ Class<User> clazz=User.class; Class<?>[] interfaces=clazz.getInterfaces(); for (Class<?> anInterface : interfaces) { System.out.println(anInterface); } System.out.println("************************ **************"); //Only the public member variables in the class can be obtained, and the common member variables in the parent class can be obtained // Field[] fields = clazz.getFields(); //Get all member variables, only the member variables of the current class Field[] declaredFields = clazz.getDeclaredFields(); for (Field field : declaredFields){ System.out.println(field); } } }
get the target constructor
- getConstructors() is the common constructor used to get the target class;
- getConstructor(parameters...) is used to get a public constructor of the target class;
- getDeclaredConstructors() is used to get all the constructors of the target class;
- getDeclaredConstructor(parameters...) is used to get a constructor of the target class;
- clazz.getConstructor(int.class) gets the int parameter constructor;
- java.lang.NoSuchMethodException: indicates that there is no such method;
package com.wei.demo1; import java.lang.reflect.Constructor; public class Test { public static void main(String[] args) throws Exception { //Class is the source of reflection. To use reflection, you must first obtain the Class object Class clazz = User.class; //Constructor is specially used to describe constructors Constructor constructor = clazz.getDeclaredConstructor(int.class); System.out.println(constructor); //Create objects with constructors System.out.println(constructor.newInstance(1 )); System.out.println(new User(1)); } }
get the method of the target class
- getMethods() gets the public methods of the target class (including the public methods of the parent class);
- getDeclaredMethod() gets all the methods of the target class (excluding the parent class);
//normal operation User user=new User(); user.rest1("name"); //reflection operation Constructor constructor=clazz.getConstructor(null); method.invock(constructor.bewInstance(null),("name"));
package com.wei.demo1; import java.lang.reflect.Method; public class User { public User(){ } public User(int id){ } @Override public String toString() { return "User{}"; } //With ginseng/without ginseng //public and private public void test1(String string){ System.out.println("test1"); } public void test2(){ System.out.println("test2"); } private void test3(Student student){ System.out.println("test3"); } private void test4(){ System.out.println("test4"); } public static void main(String[] args) throws Exception { Class clazz = User.class; Constructor constructor = clazz.getConstructor(null); User user = (User) constructor.newInstance(null); // //The method is the main body Method method2 = clazz.getMethod("test2", null); Method method3 = clazz.getDeclaredMethod("test3", Student.class); Method method4 = clazz.getDeclaredMethod("test4", null); method2.invoke(user,null); method3.invoke(user,new Student()); method4.invoke(user); } }
get member variable
NoSuchFieldException: Indicates that there is no such member variable;
package com.wei.demo1; import java.lang.reflect.Field; public class Test4 { public static void main(String[] args) throws Exception { Class clazz = Student.class; Student student = new Student(1); Student student2 = new Student(2); Field field = clazz.getDeclaredField("id"); //Brute-force reflection, private member variables can be accessed externally field.setAccessible(true); field.set(student,100); System.out.println(student); } }
Reflection provides a feature to access private information in a class externally, including member variables, methods, and constructors;
You only need to call setAccessible(true) of the corresponding resource to set violent reflection, which is generally not recommended, because it may destroy the encapsulation of the class;