Reflection (Java interview questions)

1. What is reflection?

(1) At runtime, for any class, you can know the properties and methods of this class
(2) At runtime, for any object, you can call the properties and methods of this object
(3) This dynamic acquisition of information And the function of dynamically calling object methods is called Java reflection mechanism

2. What is the role of reflection?

(1) At runtime, determine the class to which any object belongs
(2) At runtime, construct an object of any class
(3) At runtime, determine the properties and methods of any class
(4) At runtime, call The properties and methods of any object

3. Application scenarios of reflection

(1) JDBC load driver ClassForName
(2) JDK dynamic proxy uses reflection mechanism to generate proxy class

4. What are the common methods of reflection?

// Create test object by reflection
Object test = Class.forName (Test.class.getName ()). NewInstance ();
// Get service method: sayHello
Method method = test.getClass (). GetMethod ("sayHello", String .class);
// Reflect to call method
method.invoke (test, "world");

5. The advantages and disadvantages of the reflection mechanism?

Advantages: Can be dynamically executed, maximize the flexibility of Java
Disadvantages: execution is slower than ordinary Java code

6. What is the difference between .class and .getClass () and Class.forName ()?

.class gets Class object by class
name.getClass () gets Class object by instance
Class.forName () gets Class object by class fully qualified name

7. What is the difference between Class object and instance object?

Class object: A Class object is generated after each class is compiled.
Instance object: The instance object is instantiated through the Class object.
All classes are dynamically loaded into the JVM when they are first used (lazy loading)

8. What is serialization and deserialization? When is it used?

Serialization: The process of converting an object into a binary code.
(1) The serialized object needs to implement a serialization interface.
(2) To maintain the stability of the serialization process, add the serialized version number to the class.
(3) Declaration Member variables that are static and transient cannot be serialized. static member variables are attributes that describe the class level, transient means temporary data
(4) a class can be serialized, then its subclasses can also be serialized
(5) deserialization, the sequence of reading serialized objects must be consistent
Deserialization: The process of converting binary encoding into objects.
When Java objects need to be transmitted over the network or stored persistently in a file, the Java objects need to be serialized.

Published 52 original articles · Likes2 · Visits 1856

Guess you like

Origin blog.csdn.net/qq_42972645/article/details/105657939