Reflection is an important feature of the Java language. We know that before using a class, we often have already created it, such as creating a class file, and then writing some attributes, methods, etc., that is, this kind of class It is static, but the reflection mechanism allows you to create a class dynamically. In addition to dynamically creating a class, we can also dynamically obtain data of similar objects and assign these data to the newly created class, which is somewhat similar to cloning. Many times, we need this feature of dynamically creating classes. For example, when processing some businesses, but these businesses are slightly different, they often correspond to multiple classes. When processing, we have to base on different Business processing to call different classes, this time the reflection mechanism comes in handy.
The following is the description of the package java.lang.reflect in the JDK API:
Provides classes and interfaces to obtain reflection information about classes and objects. Within security constraints, reflection allows programmatic access to information about the fields, methods, and constructors of a loaded class, and allows the use of reflected fields, methods, and constructors to operate on underlying equivalents on an object.
AccessibleObject allows access checks to be suppressed if the required ReflectPermission is available.
Arrays provide static methods for dynamically creating and accessing arrays.
The classes in this package, as well as java.lang.Class, can be adapted to the needs of applications such as debuggers, interpreters, object inspectors, class browsers, and services (such as Object Serialization and JavaBeans) that need to access target objects based on public members of its runtime class) or members declared by a given class).
The following uses two simple examples to illustrate the use of reflection. First, create a Person class:
Copy the code code as follows:
package test;
public class Person {
private int age;
private String name = "";
private String[] arr = new String[2];
public Person(){}
public Person(String name,int age){
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String[] getArr() {
return arr;
}
public void setArr(String[] arr) {
this.arr = arr;
}
}
Example 1: Get the attributes and method information of the Person class. Copy the code as follows:
private static void testSimpleReflect(){
String className = "test.Person";
try {
Class c = Class.forName(className);
Field[] fields = c.getDeclaredFields();
Method[] m = c.getDeclaredMethods();
for (Field field : fields){
System.out.println(field.getName());
}
for (Method method : m){
System.out.println(m.getClass());
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
This is very simple. You can get a class through the package path where the class is located. In actual work, it is also the most used.
Example 2: Object copy Copy code The code is as follows:
@SuppressWarnings("unchecked")
public static Object copy(Object object) throws Exception {
// Get the object type
Class classType = object.getClass();
System.out.println("" + classType.getName()); // Create a new object through the default construction method
Object objectCopy = classType.getConstructor(new Class[] {})
.newInstance(new Object[] {}); // Get all properties of the object
Field fields[] = classType.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
String fieldName = field.getName();
String firstLetter = fieldName.substring(0, 1).toUpperCase(); // Get the name of the getXXX() method corresponding to the attribute
String getMethodName = "get" + firstLetter + fieldName.substring(1); // Get the name of the setXXX() method corresponding to the attribute
String setMethodName = "set" + firstLetter + fieldName.substring(1); // Get the getXXX() method corresponding to the attribute
Method getMethod = classType.getMethod(getMethodName,
new Class[] {}); // Get the setXXX() method corresponding to the attribute
Method setMethod = classType.getMethod(setMethodName,
new Class[] { field.getType() }); // Call the getXXX() method of the original object
Object value = getMethod.invoke(object, new Object[] {});
System.out.println(fieldName + ":" + value); // Call the setXXX() method of the copied object
setMethod.invoke(objectCopy, new Object[] { value });
}
return objectCopy;
}
Using reflection to copy objects, we usually don’t have to do it ourselves, because the open source system BeanUtils has already encapsulated the object copy for us. We can just call its method directly, but it is worth noting that BeanUtils is also based on the reflection mechanism. To make the package
Here is a call:
Copy the code code as follows:
public static void main(String[] args){
Person person = new Person("tom",22);
String[] strs = new String[]{"a","b"};
person.setArr(strs);
try {
Person p = (Person)copy(person);
System.out.println(p.getName()+">>"+p.getAge());
for (String str : p.getArr()){
System.out.println(str);
}
} catch (Exception e) {
e.printStackTrace();
}
// testSimpleReflect();
}