java: "Everything is an object", I feel that the Java language itself is constantly practicing this sentence.
The basis of the Java reflection mechanism comes from a Class class. We can read, instantiate, etc. each class through the methods in this class.
Object represents or encapsulates some data. After a class is loaded, jvm will create a Class object corresponding to the class (a class will only correspond to one Class object), and the entire structural information of the class will be placed in the corresponding Class object. This Class object is like a mirror, through which you can see all the information of the corresponding class.
Free learning video tutorial sharing:java video tutorial
For example:
The instantiation process of a Person:
Person person = new Person();
Apply reflection to achieve:
Class clz = null; String name = "com.zl.server.Person"; //类的地址 try { clz = Class.forName(name); //将类的地址传入 Person person = (Person)clz.getConstructor().newInstance(); //获取构造器,进行实例化 return servlet; } catch (Exception e) { e.printStackTrace(); }
The reflection mechanism will make the instantiation of classes more flexible.
In many frameworks, reflection has been widely used. We can obtain the annotations, constructors, properties, etc. of the class through Class to perform more processing.
Recommended related articles and tutorials:java introductory tutorial
The above is the detailed content of what is java reflection mechanism. For more information, please follow other related articles on the PHP Chinese website!