Reflection and annotation

Posted by synapse0 on Wed, 29 Dec 2021 02:18:11 +0100

Reflection and annotation

1. Reflection

Operate java bytecode file [class file] through reflection mechanism

- Class

- Method Class

- Constructor class

- Field class

1. 1. Reflection class: Class

Three ways to get class files

//Use the static method forname of Class ("full Class name with package name") [* * key * *]
//The forName method will load the class without creating an object [you can only execute static code blocks]
Class c1 = Class.forName("java.lang.String");

//Any object in java has a method: getClass() to get the class file
Class c2 = object.getClass();

//Any data type in java is used class attribute
Class c3 = String.class;


c1.getName();//Get the full class name [java.lang.Sting]
c1.getSimpleName();//Get simple class name [String]

What can I do to get the class file

	-  create object
	-  Reflection properties
	-  Reflection method
	-  Reflection construction method
//Create object: the newInstance method calls the construction method to create an object [cooperate with the property configuration file to create an object more flexibly]
//Object 0 = c.newInstance();
//Read property profile
//Resource binder, binding XXX Properties file
ResourceBundle bundle = ResourceBundle.getBundle("xxx");
String str = bundle.getString("key");
Class c = Class.forName(str);
Object 0 = c.newInstance();

1. 2 reflection attribute: Field

Get the properties of the class

Class c = Class.forName("xxx");


//Get the attribute of the class through the getFields method, return it as a Field array, take out the first attribute and get the attribute name
//Only public modified attributes can be obtained
//Field[] f = c.getFields();
//Field f1 = f[0];
//String str = f1.getName();

//Get all the properties through the getdeclaraedfields method
Field[] f = c.getDeclaredFields();
Field field1 = f[0];

		//Get property name
		String str = field1.getName();

		//Get the type of the attribute, return a Class through the getType method, and the obtained Class name is the attribute type name
		Class xxx = field1.getType();
		String str = xxx.getSimpleName();


		//Get the modifier of the attribute and return the number of int type. Each number is the code of the modifier. You can use the static method modifire Tostring() conversion
		int i = field1.getModifies();
		String str = Modifire.toString(i);

Get the properties of the object

Class c = Class.forName("xxx");

//create object
Object obj = c.newInstance();

//Get the name attribute of the object
Field f = c.getDeclaredFields("name");
//Assign a value to the name attribute of the obj object
f.set(obj,"zhangsan");
//Gets the value of the property
f.get(obj);


//The name attribute name and "zhangsan" can be written to the configuration file, which is more flexible




//The above can only access public attributes, and access to private attributes should break the encapsulation [violent opening is a disadvantage of the reflection mechanism and may be used by criminals]
f.setAccessible(true);

1. 3. Reflection Method:

Reflection class method

//Method to get class
Method[] m = c.getDeclaredMethod();

//Get return value type
m.getReturnType().getSimpleName();

//Get modifier
Modifire.toString(m.getModifires());

//Get parameter list of method [0 or more]
Class[] parameterTypes = m.getParameterTypes();

Reflection calls the method of the object

//create object
Object obj = c.newInstance();
//Take out the login method. The parameters are two String types
Method m = c.getDeclaredMethod("login",String.class,String.class);
//Execute the method to get the return value
Object returnValue = m.invoke(obj,"admin","123");

1. 4. Reflection construction method: Constructor

Reflection construction method

//Obtain construction method
Constructor[] con = c.getDeclaredConstructor();

//Get constructor parameter type
Class[] parameterTypes = con.getParameterTypes();

Create objects using reflection construction methods

Class c = Class.forName("xxx");


//Create object without parameters
Object o = c.newInstance();
//Object o2 = c.getDeclaredConstructor().newInstance();


//Create object with parameters
//Obtain construction method
Constructor con = c.getDeclaredConstructor(int.class,String.class);
//Call method
Object 0bj = con.newInstance(123,"zhangsan");

1. 5 get the parent class and parent interface of the class

Class c = Class.forName("xxx");

//Get the parent class of xxx class
Class superClass = c.getSuperClass();

//Get all parent interfaces implemented by xxx class
Class[] interfaces = c.getInterfaces();

2. Class loader

Tools and commands for loading classes [ClassLoad]

Three class loaders included in JDK

		- Start class loader [parent loader]
		- Extended class loader [parent loader]
		- Application class loader

Before the code is executed, all classes will be loaded into the JVM. First, they will be loaded in rt.jar through the "start class loader". If they are not found,

It will be loaded in ext/*.jar through the "extension classloader"; if it is not loaded, it will be loaded through the application classloader.

Application classes are loaded specifically from classpath.

Parental delegation mechanism

In order to ensure the security of class loading in java [for example, write a String class and implant a back door], the two parent delegation mechanism is used to load classes from the parent loader and the parent loader first

3. Notes

Annotation was introduced from JDK5

Annotation is not the program itself, but can explain the program; It can be read by other programs (compilers).

Annotation format: @ annotation name, and some parameter values can be added [@ SuppressWarnings(value = "unchecked")]

3.1 built in notes

In Java Built in annotations under Lang package

  • Override overrides the method of the parent class method
  • Deprecated indicates that the element is obsolete
  • Suppresswaiting ("all") suppress warning

3.2 yuan notes

Be responsible for annotation and binding other annotations

  • Target [define where annotations can appear]
  • Retention defines the life cycle of annotations [source < class < runtime, just use runtime, and define that annotations can still exist and be used at runtime]
  • The Documented definition annotation will be included in the javadoc
  • Inherited defines that a subclass can inherit the annotation of the parent class

3.3 user defined annotation

//Defining this annotation can be used on methods
@Target(value=ElementType.METHOD)
//Custom annotation
[Modifier ] @interface Annotation type name{}

Topics: Java