Java Road to God: Java Interview Preparation (11)

10. Annotation and reflection

10.1 The concept and function of reflection

The concept of reflection:

Reflection, a computer processing method. It is the ability of a program to access, detect and modify its own state or behavior.

Java reflection can be loaded at runtime, detect and use classes that are completely unknown during compilation.

When the program is running, you can dynamically load a class with only a name. For any loaded class, you can know all the properties and methods of this class; for any object, you can call any of its methods and properties;

After the class is loaded, an object of type Class will be generated in the heap memory (a class has only one Class object). This object contains the complete structure information of the class, and the Class object is like a mirror. Look through this mirror. To the structure of the class, so it is called: reflection.

Java reflection allows us to dynamically load a class while the program is running, and dynamically obtain the basic information and defined methods, constructors, domains, etc. of the class.

In addition to reviewing class information, you can also dynamically create class instances, execute methods of class instances, and obtain domain values ​​of class instances. Reflection gives dynamic characteristics to the static language of java.

The role of reflection:

Through reflection, the program code can access the internal information of the class loaded into the JVM

  1. Get the attribute information of the loaded class

  2. Method to get the loaded class

  3. Get the information about the construction method of the loaded class

Advantages of reflection:

Increase the flexibility of the program.

Such as struts. Requested dispatch control.

When the request comes. Struts through the query configuration file. Find the action corresponding to the request. Already method.

Then instantiate the action through reflection. And call the response method.

If reflection is not applicable, then you can only write to the code.

So, one is flexible and the other is not flexible.

It is rarely necessary to use reflection. In most cases, reflection is to improve the flexibility of the program. Therefore, it is used more in general frameworks. Because the framework has to be applicable to more situations. High requirements for flexibility.

10.2 What are the main implementation classes of Java reflection technology and what are their roles?

In the JDK, the Java reflection mechanism is mainly implemented by the following classes, which are located in the java.lang.reflect package

1) Class class: represents a class

2) Field class: member variables (attributes) representing the class

3) Method class: member method of the representative class

4) Constructor class: the construction method of the representative class

5) Array class: provides static methods to dynamically create an array and access the elements of the array

10.3 What is the role of Class? What are the methods to generate Class objects

The Class class is the origin and entry point of the Java reflection mechanism. It is used to obtain various information related to the class and provides related methods for obtaining class information. Class class inherits from Object class

The Class class is the common drawing for all classes. Each class has its own object, like the relationship between a drawing and a real object; each class can also be regarded as an object, with a common drawing Class, which stores the structural information of the class, and can retrieve the corresponding information through the corresponding method: the name of the class, Properties, methods, constructors, parent classes and interfaces

10.4 Use occasions and functions of reflection, and its advantages and disadvantages

1) Use occasion

At compile time, it is impossible to know which classes the object or class may belong to. The program only relies on runtime information to discover the true information of the object and class.

2) Main function

Through reflection, the program code can access the internal information of the class loaded into the JVM, obtain the attribute information of the loaded class, obtain the method of the loaded class, and obtain the construction method information of the loaded class

3) Advantages of reflection

Reflection improves the flexibility and scalability of Java programs, reduces coupling, and improves adaptive capabilities. It allows programs to create and control objects of any class without having to hard-code the target class in advance; reflection is not available in other common languages, such as C, C++, Fortran or Pascal

4) Java reflection technology has a wide range of applications, such as software testing; many popular open source frameworks such as Struts, Hibernate, and Spring have adopted this technology in the implementation process

5) Disadvantages of reflection

Performance issues: The use of reflection is basically an interpretation operation, which is much slower than direct code when used for field and method access. Therefore, the Java reflection mechanism is mainly used in system frameworks that require high flexibility and scalability, and it is not recommended for ordinary programs.

Using reflection will obscure the internal logic of the program: programmers want to see the logic of the program in the source code, and reflection and other technologies that bypass the source code will cause maintenance problems. The reflection code is more complicated than the corresponding direct code.

10.5 Java's reflection principle and annotation principle?

The principle of reflection: JVM generates corresponding objects through bytecode class files. Just like the normal generation of an object, it is all derived from the bytecode class file. The reason why it is called reflection is just because it is not like a normal object declaration, such as A a=new A()

10.6 What is the difference between class.forName("java.lang.String") and String.class.getClassLoader().loadClass()

10.7 How to prevent the singleton pattern from being destroyed by reflection

public class DemoModify {
    
    
    
    private static boolean flag = true;
    
    private  DemoModify() {
    
    
        synchronized (DemoModify.class) {
    
    
            if (flag == false) {
    
    
                flag = !flag;
            }else{
    
    
                throw new RuntimeException("单例模式被侵犯!");
            }
        }
    }
    
    //静态内部类
    private static class SingletonHolder{
    
    
        private static final DemoModify INSTANCE = new DemoModify();
    }
    
    public static DemoModify getInstance(){
    
    
        return SingletonHolder.INSTANCE;
    }
}

10.8 Meta annotations in java

Modification of annotations

@Target :定义自定义注解的使用范围
-类
-方法
-属性

@Retention: 定义自定义注解的生效时间
-source 只保留在源文件,编译成class文件后此注解没有
-class 检查性操作,比如@Supperesswaring
-runtime 

@Documented:生成javadoc信息

@Inherited:修饰的自定义注解可以被子类继承 

11. Keywords in Java

11.1 The role of this and super keywords

this is a reference inside the object that refers to itself, and it also solves the problem that member variables and local variables have the same name; this can call member variables but not local variables; this can also call member methods, but this can be omitted in ordinary methods, in the construction Omission is not allowed in the method, it must be the first statement of the construction method. , And this keyword is not allowed in static methods.

super represents a reference to the direct parent class object of the current object, super can call the member variables of the direct parent class (note the influence of permission modifiers, such as not being able to access private members)

Super can call the member methods of the direct parent class (note the effect of the permission modifier, such as not being able to access private members); super can call the constructor of the direct parent class, which can only be used in the constructor, and it must be the first statement.

11.2 The role of the static keyword

static can modify variables, methods, code blocks and internal classes

The static attribute belongs to this class, that is, all objects created by this class share the same static attribute. After the object is created, it can be accessed in two ways: object name, attribute name and class name. attribute name. It can also be accessed by way of class name and attribute name before creating any object.

The difference between static variables and non-static variables (both are member variables, not local variables)

1. The number of copies in the memory is different

No matter how many objects there are, there is only one static variable. For each object, there will be a separate copy of the instance variable

Static variables belong to the entire class and are also called class variables. Non-static variables belong to objects, also called instance variables

2. Different locations in the memory

2. Different locations in the memory

3. Different access methods

Instance variable: object name. variable name stu1.name="Xiao Mingming";

Static variable: object name. variable name stu1.schoolName="Xi'erqi Primary School"; such use is not recommended

Class name. Variable name Student.schoolName="Dongsanqi Primary School"; recommended

4. The time to allocate space in memory is different

Student.schoolName="Dongsanqi Primary School"; or Student stu1 = new Student("小明","男",20,98);

Static methods can also be accessed in two ways: object name, method name and class name. method name

static code block. When the class is used for the first time (may be to call static properties and methods, or create its objects), the static code block is executed, and it is executed only once, and the main function is to realize the initialization of static properties.

Static inner class: belongs to the entire outer class, not every object belonging to the outer class. Can not access the non-static members (variables or methods) of the external class, and can access the static members of the external class

11.3 The role of final and abstract keywords

Final and abstract are two keywords with opposite functions, which can be compared and memorized

Abstract can be used to modify classes and methods, but cannot be used to modify attributes and construction methods; classes modified with abstract are abstract classes and need to be inherited, and methods modified with abstract are abstract methods and need to be overridden by subclasses.

Final can be used to modify classes, methods, and attributes, but not constructors. The class modified with final cannot be inherited, the method modified with final cannot be overridden, and the value of the variable modified with final cannot be modified, so it becomes a constant.

*Special attention: *final modifies the basic type variable, its value cannot be changed, from the original variable to constant; but final modifies the reference type variable, the reference in the stack memory cannot be changed, but the attribute of the object in the heap memory pointed to The value can still be changed. E.g

class Test {
    
    
    public static void main(String[] args) {
    
    
        final Dog dog = new Dog("欧欧");
        dog.name = "美美";//正确
        dog = new Dog("亚亚");//错误
    }
}

11.4 The difference between final, finally, and finalize

Final modifier (keyword) If a class is declared as final, it means that it can no longer derive new subclasses, and cannot be inherited as a parent class, such as String class, Math class, etc. Declaring variables or methods as final ensures that they will not be changed during use. A variable declared as final must be given an initial value when it is declared, and it can only be read in subsequent references and cannot be modified. The method declared as final can also only be used, cannot be overridden, but can be overloaded. Using final modified objects, the reference address of the object cannot be changed, but the value of the object can be changed!

Finally , a finally block is provided during exception handling to perform any cleanup operations. If there is finally, the finally statement will be executed regardless of whether an exception occurs. Under normal circumstances, all related operations such as closing the physical connection (IO stream, database connection, Socket connection) are put into this code block.

Finalize method name. Java technology allows the use of the finalize() method to do the necessary cleanup work before the garbage collector clears the object from memory. The finalize() method is called before the object is deleted by the garbage collector. It is defined in the Object class, so all classes inherit it. Subclasses override the finalize() method to organize system resources or perform other cleanup tasks. Under normal circumstances, this method is called by JVM, programmers should not call it!

11.5 What if the variable is modified with final? What if the method is final modified

1. The class modified with final cannot be extended, which means that there can be no subclasses;

2. The method modified with final cannot be replaced or hidden:

① Instance methods that use final modification cannot be overridden in the subclasses of the class to which they belong;

② The static method modified with final cannot be redefined and hidden in the subclasses of the class to which it belongs;

3. Variables modified with final can only be assigned once at most, and different types of variables may be slightly different in the way of assignment:

① A static variable must be definitely assigned once (not just the default value of the type); as a static variable of a class member, the assignment can be done through an initialization expression in its declaration, or in a static initialization block; static as an interface member Variables, assignment can only be done through initialization expressions in their declarations;

② The instance variable must also be definitely assigned once (not only the type default value); the assignment can be done in its declaration through the initialization expression, or it can be done in the instance initialization block or constructor;

③ The method parameter variable is created when the method is called, and is initialized to the corresponding actual parameter value at the same time. It ends at the end of the method body, and its value cannot be changed during this period;

④ Constructor parameter variables are created when the constructor is called (through instance creation expressions or displayed constructor calls), and are initialized at the same time. They are corresponding actual parameter values ​​and terminate at the end of the constructor body. During this period, their values ​​cannot be changed. ;

⑤ The exception handler parameter variable is created when an exception is caught by the catch clause of the try statement, and at the same time it is initialized to the actual exception object, and ends at the end of the catch statement block, during which its value cannot be changed;

⑥ Local variables must be definitely assigned before their values ​​are accessed;

Guess you like

Origin blog.csdn.net/weixin_54707168/article/details/113976596