A: Junit

1. Test categories

– Black box test

  • Regardless of the logical structure and processing within the program, the input is given and the output is observed as expected

– White box test

  • Pay attention to the specific execution process of the program, and design test cases to debug the program, check whether there are bugs

2. Junit usage steps (white box test)

  1. Defining a test class (Test case)
    • Test package name: test
    • Test class name: name of the tested class +Test, for example, CalculatorTest
  2. Define test methods that can be run independently (without calling the main method)
    • Return value: void
    • Method name: test+ the name of the method being tested
    • Parameter list: empty
    • Add annotations to this method@Test

    Such as:public void testSum(){}

  3. Judge test results
    1. useAssertEquals (expected value, actual value)statements
    2. Execute test method
    3. Observe the console execution results
  • Custom methods
    1. Initialization method (example name: init)
      • Add annotations to this method@Before
      • This method is used to request resources and is executed automatically before all test methods are executed
    2. Free resource method (example name: close)
      • Add annotations to this method@After
      • Used to release resources and executed automatically when all test methods have finished executing

2: reflection

1. Reflex mechanism

  • Encapsulate the various components of a class into corresponding objects
    • benefits
      1. These objects can be manipulated while the program is running
      2. Decoupling, improve the scalability of the program

2. The three stages that Java code goes through in a computer

  1. Source code stage: on hard disk, not loaded into memory
  2. Class loader: can load. Class bytecode files into memory

3. Three ways to get a Class object

  1. Class. ForName (" full name "): loads the bytecode file into memory and returns a Class object
    • It is used to define the class name in the configuration file, read the configuration file, and load it into the memory
  2. The name of the class. The class: obtained from the class attribute of the class name
    • Mostly used when passing parameters
  3. Object. GetClass ()GetClass () of the: Object class
    • This parameter is used after an existing object
  • The Class objects obtained in the preceding three methods are the same, indicating that the same bytecode file is loaded only once during a program running

4. Function of the Class object

  1. Get member variables
    • Only public – decorated member variables can be obtained
      1. Field[] getFields()
      2. Field getField(String name)
    • Gets a member variable, without qualifiers
      1. Filed[] getDeclaredFields()
      2. Filed getDeclaredField(String name)
  2. Get constructor
    • Only public qualified constructors can be obtained
      1. Constructor<? >[] getConstructors()
      2. Constructor<T>[] getConstructor(Class<? >... parameterTypes)
    • Gets the constructor, without modifier restrictions
      1. Constructor<? >[] getDeClaredConstructors()
      2. Constructor<T>[] getClaredConstructor(Class<? >... parameterTypes)
  3. Get member method
    • Only public – decorated member methods can be obtained
      1. Method[] getMethods()
      2. Method getMethod(String name, Class<? >... parameterTypes)
    • Gets the constructor, without modifier restrictions
      1. Method[] getDeclaredMethods()
      2. Method getDeclaredMethod(String name, Class<? >... parameterTypes)
  4. Gets the full class name
    • String getName()

5. The function of the encapsulated object

  • You can use the privatet-modified member variable (constructor/member method) once you have obtained itsetAccessible(true)Statement (violent reflection) ignores security checks for access permission modifiers
  1. Field: member variable
    1. Setting:void set(Object obj, Object value)
    2. Get the value:get get(Object obj)
  2. (4) Constructor
    1. Create an object:newInstance(Object... initargs)
    • If an object is created using the null parameter constructor, the operation can be simplified:NewInstance () for Class objectsmethods
  3. Method: Method object
    1. Execute this method:Object invoke(Object obj, Object... args)
    2. Obtain method name:String getName()

6. Reflection cases

  • Requirement: Write a simple framework that can help you create objects of any type and execute any of its methods without changing any of its code
  • Step analysis
    1. The full class name (package name) of the class that will need to create the object. Class name) and the methods that need to be executed are first defined in the configuration file
    2. Load and read the configuration file in the program
    3. Use reflection to load class files into memory
    4. Create the object and execute the method
  • The sample code
    import java.io.InputStream;
    import java.lang.reflect.Method;
    import java.util.Properties;
    
    /* Config file: pro.properties content: className = demo2.student methodName = study */
    public class ReflectTest {
        public static void main(String[] args) throws Exception {
            // Get the class loader
            ClassLoader classLoader = ReflectTest.class.getClassLoader();
            // Get the byte input stream of the configuration file
            InputStream inputStream = classLoader.getResourceAsStream("pro.properties");
            // Create a configuration file object
            Properties properties = new Properties();
            // Load the byte input stream of the configuration file
            assertinputStream ! =null;
            properties.load(inputStream);
            // Read the configuration file to get the class name
            String className = properties.getProperty("className");
            // Load the class into memoryClass<? > class1 = Class.forName(className);// Create an object for the class
            Object instance = class1.newInstance();
            // Read the configuration file to obtain the method name
            String methodName = properties.getProperty("methodName");
            // Get the object of the method
            Method method = class1.getMethod(methodName);
            // Execute methodmethod.invoke(instance); }}Copy the code
  • Benefits: Changes only require changes to the configuration file, not to the code, improving the scalability of the program

3: annotation

1. The role

  1. Compile the inspection
    • Allow the compiler to perform basic compilation checks through annotations identified in the code
  2. Written document
    • Generate doc documents from annotations identified in the code
  3. The code analysis
    • Code is analyzed by annotations identified in the code

2. Predefined annotations in the JDK

  1. @Override
    • The method representing the annotation identity overrides the parent class (interface)
  2. @Deprected
    • Indicates that the content of the annotation identifier is obsolete (it is still available, but there is a better alternative)
  3. @SuppressWarnings
    • Suppress all types of warnings:@SuppressWarnings("all")

3. Custom annotations

  1. format
    Yuan notespublic @interfaceAnnotation name {attribute list}Copy the code
  2. nature
    • An Annotation is essentially an interface that inherits the Annotation interface by default
    • Public interface name annotation extends Java. Lang. The annotation. The annotation {}
  3. attribute
    • That is, abstract methods in interfaces
    • requirements
      1. The return value of the property has only the following values
        • Basic data types
        • String
        • The enumeration
        • annotations
        • An array of the above types
      2. If you define an attribute, you need to assign a value to it when you use it (in general)
        • If the default keyword is used to assign the default initial value to the attribute when defining it, it can be assigned with or without the attribute
        • If only one attribute needs to be assigned, and the name of the attribute is value, the assignment can be omittedvalue=, directly assign the value
        • When assigning values to arrays, multiple values need to be wrapped with {}. If there is only one value in the array, {} can be omitted
        • The sample code
          public @interface AnnotationTest {
              public abstract String[] value();
          }
          
          @AnnotationTest("zs")
          public class Test {}Copy the code
  4. Yuan notes
    • Concept: a note used to describe a note
    • classification
      1. @Target:Describe where the annotation can work
        public @interface Target {
            ElementType[] value();
        }
        Copy the code
      • Where enumeration classesElementTypeThe value of aTYPE(class),FIELD(member variable),METHOD(method), for example@Target({ElementType.TYPE, ElementType.METHOD})
      1. @Retention:Describe the phase in which annotations are retained
        public @interface Retention {
            RetentionPolicy value(a);
        }
        Copy the code
      • Where enumeration classesRetentionPolicyThe value of aSOURCE(Source code),CLASS(Class object stage),RUNTIME(runtime phase), used for custom annotations@Retention(RetentionPolicy.RUNTIME), indicating that the currently described annotations are retained in the class bytecode file and read by the JVM
      1. @Documented:Describes whether annotations will be extracted into the API document
      2. @Inherited:Describes whether annotations are inherited by subclasses
  5. Parsing the annotation
    • To parse (use) annotations in a program is to get the values of the attributes defined in the annotations
    • Annotations are mostly used to replace configuration files
    • Steps:
      1. Gets the bytecode file object where the annotation is applied (CLASS/FIELD/METHOD)
      2. Get the annotation object
      3. Call the abstract method defined in the annotation object to get the return value
    • The sample code
      • Use annotations to implement the requirements of the reflection case
        import java.lang.reflect.Method;
        
        @TestAnnotation(className = "demo3.Demo1", methodName = "method1")
        public class Test {
            public static void main(String[] args) throws Exception {
                // Get the bytecode file object of the class
                Class<Test> testClass = Test.class;
                // Get the annotation object
                TestAnnotation annotation = testClass.getAnnotation(TestAnnotation.class);
                // Call the abstract method defined in the annotation object to get the return value
                String className = annotation.className();
                String methodName = annotation.methodName();
                // Load the class into memoryClass<? > aClass = Class.forName(className);// Create an object for this class
                Object instance = aClass.newInstance();
                // Get the method object
                Method method = aClass.getMethod(methodName);
                // Execute methodmethod.invoke(instance); }}Copy the code