当前位置:网站首页>Annotation and reflection
Annotation and reflection
2022-07-03 13:12:00 【Tolerance speech】
1、 annotation (Annotation)
1. summary
- Not the program itself , The procedure can be explained ( Points and notes (comment) It's like )
- Can be used by other programs ( such as : Compiler, etc. ) Read
- Format :”@ Comment name “ There is... In the code , You can also add some parameter values
- Annotations also have check and constraint functions
- Annotation parameters have no order
- Reflection mechanism for reading annotations
2. Built-in annotations
@Override: Rewriting methods
@Deprecated: Not recommended , Usually because it is dangerous or there is a better choice
@SuppressWarnings: Used to suppress compile time warnings , Need to add parameters
package Annotation;
import java.util.ArrayList;
public class Demo01 extends Object {
@Override
public String toString() {
return super.toString();
}
@Deprecated
public static void test(){
System.out.println("h");
}
@SuppressWarnings("all")
public void test1(){
ArrayList list = new ArrayList();
}
}
3. Yuan notes
Meta annotation is responsible for Notes other notes ,java Defined 4 A standard meta-annotation type
- @Target: Used to describe the scope of use of annotations ( Indicates where our annotations can be used )
- @Retention: Indicates at what level the annotation information needs to be saved , Used to describe the life cycle of annotations ( Indicates where our annotation is still valid )
- SOURCR Source code <CLASS<RUNTIME
- @Inherited: Note that subclasses can Inherit The annotation in the parent class
- @Documented: Indicates whether to generate our annotation in JAVAdoc in
4. Custom annotation
keyword :@interface
package Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
public class Demo02 {
// Annotations can show assignments , If there is no default value , We have to assign values to annotations
@MyAnnotation(name = "mo")
public void test(){
}
// If only one value is value You can not write the parameter name
@MyAnnotation1("")
public void test1(){
}
}
// Customize an annotation
@Target(value = {
ElementType.METHOD,ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
@interface MyAnnotation{
// Annotated parameters : Parameter type + Parameter name ();
String name() default ""; // The default parameter is empty
int age() default 0;
int id() default -1; // If the default is -1 nonexistence , similar indexof If you can't find it, go back -1
String[] schools() default {
" Tsinghua University "};
}
@Target(value = {
ElementType.METHOD,ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
@interface MyAnnotation1{
String value();
}
2. The reflex mechanism (Reflection)
1. static state VS Dynamic language
Dynamic language : When running code, you can change its structure according to certain conditions ,C# ,Python,JavaScript.
Static language : A language whose runtime structure cannot be changed ,Java,C,C++
2. summary
Reflection yes Java Seen as the key to dynamic language
Object In the class getClass() Method
After loading the class , In the method area of heap memory Class Type object ( There is only one class Class object ), This object contains the complete class structure information , We can see the structure of the class through this object . This object is like a mirror , Look through this mirror to see the structure of the class , All is called reflection .
3.Class
1. Get the reflection object Class
package Reflection;
public class Demo01 {
public static void main(String[] args) throws ClassNotFoundException {
// Get the... Of the class by reflection class object
// After a class is loaded , The entire structure of a class is encapsulated in Class In the object
Class c1 = Class.forName("Reflection.Demo01");
System.out.println(c1);
}
}
// Entity class
class User{
private String name;
private int id;
private int age;
public User() {
}
public User(String name, int id, int age) {
this.name = name;
this.id = id;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" + "name='" + name + '\'' + ", id=" + id + ", age=" + age + '}';
}
}
2. obtain Class Class
package Reflection;
public class Demo02 {
public static void main(String[] args) throws ClassNotFoundException {
Person person = new Student();
System.out.println(" This man is :"+person.name);
// Method 1 : Get... By object
Class c1 = person.getClass();
System.out.println(c1.hashCode());
// Method 2 :forname get
Class c2 = Class.forName("Reflection.Student");
System.out.println(c2.hashCode());
// Method 3 : By class name .class. This is a static property , Every method has
Class c3 = Student.class;
System.out.println(c3.hashCode());
// The wrapper class of the basic built-in type has a Type attribute
Class c4 = Integer.TYPE;
System.out.println(c4);
// Get the parent type
Class c5 = c1.getSuperclass();
System.out.println(c5);
}
}
class Person{
public String name;
public Person() {
}
public Person(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" + "name='" + name + '\'' + '}';
}
}
class Student extends Person{
public Student(){
this.name=" Student ";
}
}
class Teacher extends Person{
public Teacher(){
this.name=" teacher ";
}
}
3. All types of Class object
package Reflection;
import java.lang.annotation.ElementType;
public class Demo03 {
public static void main(String[] args) {
Class c1 =Object.class; // class
Class c2 =Comparable.class; // Interface
Class c3 =String[].class; // One dimensional array
Class c4 =int[][].class; // Two dimensional array
Class c5 =Override.class; // annotation
Class c6 = ElementType.class;// enumeration
Class c7 =Integer.class; // Basic data type
Class c8 =void.class; //void
Class c9 =Class.class; //Class
System.out.println(c1 );
System.out.println(c2 );
System.out.println(c3 );
System.out.println(c4 );
System.out.println(c5 );
System.out.println(c6 );
System.out.println(c7 );
System.out.println(c8 );
System.out.println(c9 );
// Two arrays with different lengths ,class Are they the same?
// summary : As long as the element type is the same as the dimension, it is one class
int[] a = new int[10];
int[] b = new int[100];
System.out.println(a.getClass().hashCode());
System.out.println(b.getClass().hashCode());
}
}
4. Class load memory analysis
1. Three steps
When the system actively uses a class , If the class has not yet been loaded into memory , Then the system will initialize the class through the following three steps .
Class load (Load)--------- Class like class File read into memory , And create a java.lang.Class object , This is done by the class loader .
Class link (Link)---------- Merge the binary data of a class into JRE in .
Class initialization (Initialize)------JVM Responsible for class initialization .
package Reflection;
public class Demo04 {
public static void main(String[] args) {
A a = new A();
System.out.println(A.m);
}
}
class A{
static {
System.out.println("A Class static block initialization ");
m = 200;
}
static int m = 100;
public A() {
System.out.println("A The parameterless construction initialization of ");
}
}
/* summary : 1. Load into memory , Will produce a class corresponding to Class object 2. link , At the end of the link m=0 3. initialization : class constructor <clinit>(){ System.out.println("A Class static block initialization "); m = 200; m=100; } m=100; */
2. Analysis class initialization
Active citation
When the virtual machine starts , Initialize first main The class of the method
new An object of a class
Call static members and static methods of the class
Make a reflection call to the class
When initializing a class , If its parent class is not initialized, its parent class will be initialized first
package Reflection; public class Demo05 { static { System.out.println("main Class loaded "); } public static void main(String[] args) throws ClassNotFoundException { // Active citation Son son = new Son(); // Reflection also produces active references Class.forName("Reflection.Son"); } } class Father{ static { System.out.println(" The parent class is loaded "); } } class Son extends Father{ static { System.out.println(" Subclasses are loaded "); } }
Passive citation ( No class reference will be generated )
Visit one Static domain when , Only classes that actually declare this domain will be initialized . For example, reference the static variable of the parent class through the subclass , Subclasses don't initialize .
adopt Array Define class references , Initialization of this class will not be triggered
quote Constant Initialization of this class will not be triggered ( Constants are in the constant pool during the link phase )
package Reflection; public class Demo05 { static { System.out.println("main Class loaded "); } public static void main(String[] args) throws ClassNotFoundException { System.out.println(Son.b); // Output results :main Class loaded The parent class is loaded 2 Son[] sons = new Son[5]; // Just a space , Classes are not loaded . Output results :main Class loaded System.out.println(Son.M); // Output results :main Class loaded 1 } } class Father{ static int b=2; static { System.out.println(" The parent class is loaded "); } } class Son extends Father{ static { System.out.println(" Subclasses are loaded "); } static final int M=1; }
3. Class loader
Class cache : The standard JavaSE The loader can find classes as required , But once a class is loaded into the classloader , It will continue to load ( cache ) A span . however JVM The garbage collection mechanism can recycle these Class object .
classification :C:\Program Files\Java\jre1.8.0_131\lib
- Boot class loader :JVM Bring their own , be responsible for Java Platform core library , Cannot read
- Extend the classloader :
- system class loader : The most commonly used loader
package Reflection;
public class Demo06 {
public static void main(String[] args) throws ClassNotFoundException {
// Get the loader of the system class
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
System.out.println(systemClassLoader);//[email protected]
// Gets the parent class loader of the loader of the system class ---> Extended loader
ClassLoader parent = systemClassLoader.getParent();
System.out.println(parent); //[email protected]
// Get the parent loader of the extension class loader ---> Root loader (c/c++)
ClassLoader parent1 = parent.getParent();
System.out.println(parent1); //null
// Test which loader the current class is loaded by
ClassLoader c1 = Class.forName("Reflection.Demo06").getClassLoader();
System.out.println(c1);
// test JDK Which loader loads the inner class
ClassLoader c2 = Class.forName("java.lang.Object").getClassLoader();
System.out.println(c2);
// How to get the path that the system class loader can load
System.out.println(System.getProperty("java.class.path"));
}
}
5. operation Class
1. Get the runtime structure of the class
package Reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Demo07 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
Class c1 = Class.forName("Reflection.User");
// Get the name of the class
System.out.println(c1.getName());
System.out.println(c1.getSimpleName());
// Get the properties of the class
Field[] fields = c1.getFields(); // We can only find public attribute
fields = c1.getDeclaredFields(); // Find all properties
for (Field field : fields) {
System.out.println(field);
}
// Find the specified attribute
Field name = c1.getDeclaredField("name");
System.out.println(name);
// The way to get the class
Method[] methods = c1.getMethods(); // Get all of this class and its parent class public Method
for (Method method : methods) {
System.out.println(" natural :"+method);
}
methods = c1.getDeclaredMethods(); // Get all the methods of this class
for (Method method : methods) {
System.out.println("getDeclaredMethods:"+method);
}
// Get the specified method
Method getName = c1.getMethod("getName", null);
Method setName = c1.getMethod("setName", String.class);
System.out.println(getName);
System.out.println(setName);
// Get the specified constructor
Constructor[] constructors = c1.getConstructors();
for (Constructor constructor : constructors) {
System.out.println(constructor);
}
constructors = c1.getDeclaredConstructors();
for (Constructor constructor : constructors) {
System.out.println("#"+constructor);
}
// Get the specified constructor
Constructor declaredConstructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
System.out.println(" Appoint :"+declaredConstructor);
}
}
2. Create objects dynamically
Create object of class : call Class Object's newInstance() Method
Class must have a parameterless constructor
The constructor access permission of the class should be sufficient
package Reflection; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Demo08 { public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException { // get Class object Class c1 = Class.forName("Reflection.User"); //1. Construct an object User user1 = (User) c1.newInstance(); System.out.println(user1); //2. Create objects through constructors Constructor constructor= c1.getDeclaredConstructor(String.class, int.class, int.class); User user2 = (User) constructor.newInstance("xiao", 007, 18); System.out.println(user2); //3. Call normal methods through reflection User user3 = (User) c1.newInstance(); Method setName = c1.getMethod("setName", String.class); //invoke: Activation means //( object ,” Value of this method “) setName.invoke(user3,"xiao"); System.out.println(user3.getName()); //4. Operate attributes through reflection User user4 = (User) c1.newInstance(); Field name = c1.getDeclaredField("name"); // Private properties cannot be manipulated directly , Turn off the security check of the program name.setAccessible(true);// Turn off security detection name.set(user4,"x"); System.out.println(user4.getName()); } }
3. Performance analysis
Common method , Reflection method , Turn off security detection .
package Reflection;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Demo09 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
test1();
test2();
test3();
}
// Common method
public static void test1(){
User user = new User();
long startTime = System.currentTimeMillis();
for (int i = 0; i < 100000000; i++) {
user.getName();
}
long endTime = System.currentTimeMillis();
System.out.println(" The time taken by the ordinary method :"+(endTime-startTime)+"ms");//0ms
}
// Reflection method
public static void test2() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
User user = new User();
Class c = user.getClass();
Method getName = c.getDeclaredMethod("getName", null);
long startTime = System.currentTimeMillis();
for (int i = 0; i < 100000000; i++) {
getName.invoke(user,null);
}
long endTime = System.currentTimeMillis();
System.out.println(" Reflection method takes time :"+(endTime-startTime)+"ms");//410ms
}
// Turn off security detection
public static void test3() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
User user = new User();
Class c = user.getClass();
Method getName = c.getDeclaredMethod("getName", null);
getName.setAccessible(true);
long startTime = System.currentTimeMillis();
for (int i = 0; i < 100000000; i++) {
getName.invoke(user,null);
}
long endTime = System.currentTimeMillis();
System.out.println(" Time taken to close the detection method :"+(endTime-startTime)+"ms");//220ms
}
}
4, Get generic information
ParameterizedType: Represents a parameterized type .
package Reflection;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
public class Demo10 {
public void test1(Map<String,User> map, List<User> list){
System.out.println("t1");
}
public Map<String,User> test2(){
System.out.println("t2");
return null;
}
public static void main(String[] args) throws NoSuchMethodException {
Method method = Demo10.class.getMethod("test1", Map.class, List.class);
Type[] genericParameterTypes = method.getGenericParameterTypes();
for (Type genericParameterType : genericParameterTypes) {
System.out.println("#"+genericParameterType);
if (genericParameterType instanceof ParameterizedType){
Type[] actualTypeArguments = ((ParameterizedType) genericParameterType).getActualTypeArguments();
for (Type actualTypeArgument : actualTypeArguments) {
System.out.println(actualTypeArgument);
}
}
}
method = Demo10.class.getMethod("test2",null);
Type genericReturnType = method.getGenericReturnType();
if (genericReturnType instanceof ParameterizedType){
Type[] actualTypeArguments = ((ParameterizedType) genericReturnType).getActualTypeArguments();
for (Type actualTypeArgument : actualTypeArguments) {
System.out.println(actualTypeArgument);
}
}
}
}
5. Reflection operation comment
package Reflection;
import java.lang.annotation.*;
import java.lang.reflect.Field;
public class Demo11 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class c = Class.forName("Reflection.Student1");
// Get annotations by reflection
Annotation[] annotations = c.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
// Get annotated value value
Tablel tablel = (Tablel) c.getAnnotation(Tablel.class);
String value = tablel.value();
System.out.println(value);
// Get the annotation specified by the class
Field f = c.getDeclaredField("name");
Fields annotation = f.getAnnotation(Fields.class);
System.out.println(annotation.columnName());
System.out.println(annotation.length());
System.out.println(annotation.type());
}
}
@Tablel("db_student")
class Student1{
@Fields(columnName = "db_name",type = "varchar",length = 3)
private String name;
@Fields(columnName = "db_id",type = "int",length = 10)
private int id;
@Fields(columnName = "db_age",type = "int",length = 5)
private int age;
public Student1() {
}
public Student1(String name, int id, int age) {
this.name = name;
this.id = id;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" + "name='" + name + '\'' + ", id=" + id + ", age=" + age + '}';
}
}
// Annotation of class name
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Tablel{
String value();
}
// Comment for attribute
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Fields{
String columnName();// form
String type();
int length();
}
边栏推荐
- Export the entire Oracle Database
- Sword finger offer 15 Number of 1 in binary
- 【R】 [density clustering, hierarchical clustering, expectation maximization clustering]
- Sword finger offer14 the easiest way to cut rope
- Flink SQL knows why (VIII): the wonderful way to parse Flink SQL tumble window
- mysqlbetween实现选取介于两个值之间的数据范围
- 2022-02-13 plan for next week
- Sword finger offer 16 Integer power of numeric value
- Flink SQL knows why (17): Zeppelin, a sharp tool for developing Flink SQL
- Four problems and isolation level of MySQL concurrency
猜你喜欢
我的创作纪念日:五周年
[review questions of database principles]
Seven second order ladrc-pll structure design of active disturbance rejection controller
[email protected]奇安信:透视俄乌网络战 —— 网络空间基础设施面临的安全对抗与制裁博弈..."/>
开始报名丨CCF C³[email protected]奇安信:透视俄乌网络战 —— 网络空间基础设施面临的安全对抗与制裁博弈...
February 14, 2022, incluxdb survey - mind map
Deeply understand the mvcc mechanism of MySQL
35道MySQL面试必问题图解,这样也太好理解了吧
人身变声器的原理
解决 System has not been booted with systemd as init system (PID 1). Can‘t operate.
Sword finger offer 14- ii Cut rope II
随机推荐
2022-01-27 use liquibase to manage MySQL execution version
Method overloading and rewriting
2022-02-13 plan for next week
2022-02-09 survey of incluxdb cluster
Seven habits of highly effective people
Kotlin - 改良装饰者模式
Flink SQL knows why (VIII): the wonderful way to parse Flink SQL tumble window
Flink SQL knows why (7): haven't you even seen the ETL and group AGG scenarios that are most suitable for Flink SQL?
[Database Principle and Application Tutorial (4th Edition | wechat Edition) Chen Zhibo] [Chapter III exercises]
When we are doing flow batch integration, what are we doing?
【習題五】【數據庫原理】
【习题五】【数据库原理】
When the R language output rmarkdown is in other formats (such as PDF), an error is reported, latex failed to compile stocks Tex. solution
The upward and downward transformation of polymorphism
01 three solutions to knapsack problem (greedy dynamic programming branch gauge)
CVPR 2022 图像恢复论文
显卡缺货终于到头了:4000多块可得3070Ti,比原价便宜2000块拿下3090Ti
[judgment question] [short answer question] [Database Principle]
Flink SQL knows why (19): the transformation between table and datastream (with source code)
Kotlin - improved decorator mode