Article Directory
What's in Java reflection?
JAVA reflection mechanism is in the operating state, for any class, are made known to all properties and methods of this class; for any object, are able to call any of its methods and properties; this information acquired dynamically and dynamic invocation a method of object function called reflection mechanism java language.
It means in the JVM run-time, dynamic program can get all the information of a class. Java object role is accessed by reflection properties, methods, construction method and the like;
Java reflection mechanism usage scenarios
The most classic is the JDBC
load drivers Class.forName(... ...);
and Spring
of IOC
, as well as to use more or less reflected in a lot of the framework.
SpringIOC
SpringIOC
The emergence of liberation in a new
way to get the object, the relationship between each of the bean (entity classes) and bean (the entity) to a third party container management. The traditional Spring
project, a xml
fashion statement as a configuration file Bean
and then through the 容器.getBean("one");
acquisition target.
Thinking: SpringIOC
the underlying implementation idea is kind of how?
Traditional Spring
project using the XML
configuration file, which defines a number of statements Bean
, we look at XML
the file Bean
structure that contains the Class
attributes id
property.
The core idea is to instantiate reflection Bean
, it is to obtain the final container .getBean (String bean) manner to an object. Reflecting only need to be able to instantiate the class path of the target object, but the properties are already stored in the xml
configuration file, so we need to use xml
analytical techniques to read xml
files.
We first customize a container object, a container object contains a private property path, as the structure of the object to the Senate, this path represents the path of the project. Then create a getBean(String beanId)
method.
Roughly Code:
// 容器对象
public class MyXMLContext {
private String xmlPath;
public MyXMLContext(String xmlPath) {
this.xmlPath = xmlPath;
}
public Object getBean(String beanId) throws DocumentException, ClassNotFoundException, NoSuchFieldException,
SecurityException, IllegalArgumentException, IllegalAccessException, InstantiationException {
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(this.getClass().getClassLoader().getResourceAsStream(xmlPath));
Element rootNode = document.getRootElement();
List<Element> childElements = rootNode.elements();
Object bean = null;
for (Element child : childElements) {
String xmlbeanId = child.attributeValue("id");
if (!beanId.equals(xmlbeanId)) {
continue;
}
String beanClassPath = child.attributeValue("class");
Class<?> forName = Class.forName(beanClassPath);
bean = forName.newInstance();
List<Element> e = child.elements();
for (Element element : e) {
String name = element.attributeValue("name");
String value = element.attributeValue("value");
Field field = forName.getDeclaredField(name);
field.setAccessible(true);
field.set(bean, value);
}
}
return bean;
}
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException,
IllegalArgumentException, IllegalAccessException, InstantiationException, DocumentException {
MyXMLContext appLication = new MyXMLContext("user.xml");
Object bean = appLication.getBean("darian");
UserEntity user = (UserEntity) bean;
System.out.println(user.toString());
}
}
// 实体类对象,省略了get/set/toString及构造方法
public class UserEntity {
private String userId;
private String userName;
}
// xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="darian" class="entity类路径">
<property name="userId" value="1"></property>
<property name="userName" value="小明"></property>
</bean>
<bean id="coco" class="entity类路径">
<property name="userId" value="2"></property>
<property name="userName" value="小红"></property>
</bean>
</beans>
Summarizes the SpringIOC
underlying implementation principles:
- Reads the
XML
configuration file - According to
beanId
locatebean
configuration, and obtain profileclass
address - Using the
Java
reflection technique instantiate an object - Get property configuration using a reflection technique assignment
For more details:
- Use of the incoming parameter acquisition
xml
stream file and usingdom4j
parsed intoDocument
objects - For
Document
obtaining the root element of the object subject<beans>
to the following tag traverse, it determines whether there is matchingid
. - If you find the corresponding
id
equivalent to find anElement
element, we began to create objects, to acquireclass
property, create an object based on property values by the reflection. - Traversing
<bean>
the labelproperty
tab, and the attribute assignment. Note that requires separate treatmentint
,float
type of property, because inxml
the configuration of these attributes are configured in the form of a string, thus requiring additional treatment. - If the property
property
tag hasref
the attribute, the value of a property is described an object, in accordance withid
(ref
to obtain the value of the property)ref
corresponding to the object, to give attribute assignment. - Returns the object created, if no corresponding
id
or<beans>
not the sub-tab returnsnull
This is SpringIOC
roughly a realization of the idea, but now most are already using the SpringBoot
project uses annotations @Autowired
way.
About notes in this regard will continue to follow ...