The key reflection mechanism of salary increase attracts the project manager's attention to you, and the salary increase is within reach!!!!

preface

For example, I was asked by the interviewer a few days ago what is reflection???

And my answer is!!!

Reflection is the key of dynamic language. Reflection allows programs to obtain the internal information of any class with the help of Reflection API during execution, and can directly operate the internal properties and methods of any Xi object.

1. Functions provided by java reflection

  • Determine the class of any object at run time
  • Construct an object of any class at run time
  • Judge the member variables and methods of any class at run time
  • Call the member variables and methods of any object at run time

2. Common API for radiation

  • java.lang.Class: represents a class
  • java.lang.reflect.Method: represents the method of the class
  • java.lang.reflect.Field: represents the member variable of the class
  • java .lang.reflect.Construct: represents the construction method of the class

3.java.lang.Class

We create a class and compile (Javac.exe) to generate the corresponding Class file. Then we use Java Exe load (JVM class loader) this Class file. This After the class file is loaded into memory, it is a runtime class. Stored in the buffer, class allows you to find the completion information of a class through an instantiated object data.

Class functions:

  • 1. Each runtime class is loaded only once!
  • 2. Obtain the complete structure of the corresponding runtime class (attribute, method, constructor, inner class, parent class, package, exception, annotation...) ​
  • 3. Call the specified structure (property, method, constructor) of the corresponding runtime class
  • 4. Reflection application: dynamic proxy

4. Get the Class object.

1. Call the of the runtime class itself Class attribute

Class<Person> personClass01 = Person.class;

2. Through an object of the runtime class

Person person = new Person();
Class<? extends Person> aClass = person.getClass();

3. Pass class forName("com.jdy.bean.Dog")

Class<?> aClass1 = Class.forName("com.jdy.bean.Dog");

4. Pass class loader

ClassLoader classLoader = this.getClass().getClassLoader();

5. Common methods of class

public Constructor<?>[] getConstructors() throws SecurityException //Gets all constructs of the class
public Field[] getDeclaredFields() throws SecurityException//Get all the properties in the class
public Field[] getFields() throws SecurityException //Get all inherited properties
public Method[] getMethods() throws SecurityException//Gets all the methods in a class
public Class<?>[] getInterfaces() //Gets all interfaces implemented by the class
public native Class<? super T> getSuperclass();//Gets the parent class of the class
//Join Java development exchange sample: 593142328 blowing water and chatting together

6.Class application

(1) Instantiate objects by parameterless construction

String packageName ="com.jdy.bean.Dog";
Class<?> aClass = Class.forName(packageName);
Dog dog = (Dog)aClass.newInstance(); //Using newInstance() must ensure that there is a parameterless constructor in the instantiated class

(2) Call a parameterized constructor to instantiate an object

public int getModifiers()//Gets the modifier of the constructor
public String getName()//Gets the name of the constructor
public Class<?>[] getParameterTypes()//Gets the parameter type of the constructor
public T newInstance(Object ... initargs)//Like construction methods, pass in parameters to instantiate objects

<Dog> constructor = (Constructor<Dog>) aClass.getConstructor(String.class, String.class, String.class);
Dog dog1 = constructor.newInstance("Er Gouzi", "Black back", "8");

(3) Get class structure

  • Constructor: represents the constructor of the class
  • Field: represents the property of the class
  • Method: represents the method of the class

Get all implemented interfaces

[] interfaces = aClass.getInterfaces();

Get parent class

Class<?> superclass = aClass.getSuperclass();

Get all constructors

Constructor<?>[] constructors = aClass.getConstructors();

Converts the access modifier from numeric to readable

int modifiers = declaredField.getModifiers();
System.out.println("modifiers = " + Modifier.toString(modifiers));

Get all the ways

Method[] methods = aClass.getMethods();

Get all properties

  //Get the public properties in the implemented interface or parent class
Field[] fields = aClass.getFields(); //Get all the attributes in this class
Field[] declaredFields = aClass.getDeclaredFields();

Common methods of Field

//Get the specific content of the attribute in an object 
public Object get(Object obj)throws IllegalArgumentException, IllegalAccessException 
//Set the specific content of the property in the specified object
public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException
 //Get the modifier of the attribute
public int getModifiers() //Returns the name of the property
public String getName() //Determine whether the property is accessible externally
public boolean isAccessible() //Sets whether a property can be used by an external method
public void setAccessible(boolean flag) throws SecurityException
//Join Java development exchange sample: 593142328 blowing water and chatting together

(4) By reflecting the methods in the class to be used

Method destory_method = aClass.getMethod("destory_method"); //The parameter of the invoke method is an instantiated object
Object invoke = destory_method.invoke(aClass.newInstance());

(5) Manipulate properties through methods

In reflection, the set()/get() provided by the Field class is used to set and obtain the property content, but the properties in the class are set to private access permissions. Therefore, when using the set()/get() method, first use the setAccessible(true) in the Field(), and the method sets the properties to be operated to be externally accessible.

Field field0 = personClass.getDeclaredField("address"); //todo what check
field0.setAccessible(true);
field0.set(person,"xian");
System.out.println(person);

Generally, the above methods are not recommended for assigning values to the properties of a class. Because the access rights of the properties are expanded, it is recommended to use the getter/setter methods of the properties in the class

5.ClassLoader: class loader. Class loader is used to load classes into memory. The JVM specification defines two types of class loaders: bootstrap and user defind class loader. The JVM will generate an initialization loader hierarchy composed of three class loaders at runtime

Bootstrap ClassLoader: Bootstrap ClassLoader: written in C + +, it is the class loader of jVM, which is responsible for loading the core class library of JAVA platform. The loader cannot get directly data

>//3. The boot class loader cannot directly obtain
ClassLoader parent1 = parent.getParent();
System.out.println("bootstrap class loader  = " + parent1);//null

Extension ClassLoader: it is responsible for the jar package under jre/lib/ext directory or - D Java Ext.dirs package the jar in the specified directory into the working library

//2. Get extension class loader
ClassLoader parent = loader.getParent();
System.out.println("extensions class loader  = " + parent);

System ClassLoader: system class loader, responsible for java -classpath or - D Java class. The classes and jar s in the directory known by path are packaged into the work, which is the most commonly used loader

//1. Get system class loader
ClassLoader loader = ClassLoader.getSystemClassLoader();
System.out.println("system class loader  = " + loader);

Gets the class loader for an instance

Person person = new Person();
Class<? extends Person> aClass = person.getClass();
ClassLoader classLoader = aClass.getClassLoader();
System.out.println("Perosn Class loader = " +classLoader);
aClass1 = Class.forName("com.jdy.bean.Dog");
ClassLoader classLoader1 = aClass1.getClassLoader();
System.out.println("Dog Class loader = " + classLoader1);

Class loader with IO

ClassLoader classLoader2 = this.getClass().getClassLoader();
InputStream resourceAsStream = classLoader2.getResourceAsStream("test.properties");
Properties properties = new Properties();
properties.load(resourceAsStream);

Some high-frequency interview questions (all sorted into documents) collected in 2021 have a lot of dry goods, including detailed explanations of mysql, netty, spring, threads, spring cloud, jvm, source code and algorithms, as well as detailed learning plan, interview question sorting, etc. for friends who need to obtain these contents, please add Q sample: 593142328

Keywords: Java Programming jvm Class architecture

Added by pelleas on Wed, 19 Jan 2022 03:38:15 +0200