Java Reflection mechanism (Reflection) analysis

  • 2020-04-01 03:21:30
  • OfStack

Reflection is an important feature of the Java language. We know that we usually create a class before we use it. For example, we create a class file, and then we write some properties, methods, and so on. In addition to dynamically creating a class, we can also dynamically take data from similar objects and assign that data to the newly created class, which is a bit like cloning. In many cases, we need this dynamic class creation feature, such as when we are dealing with some business, but the business is slightly different, often corresponding to more than one class, in the processing, we have to call different classes according to different business processing, this reflection mechanism is useful.

The following is a description of the package java.lang.reflect in the JDK API:

Provides classes and interfaces to get reflection information about classes and objects. Within security constraints, reflection allows programmatic access to information about the fields, methods, and constructors of the loaded class, and allows the use of reflection fields, methods, and constructors to manipulate basic equivalents on objects.

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 examiners, Class browsers, and services (such as Object Serialization and javabeans, which require access to public members of the target Object (based on its runtime classes) or members of a given Class declaration).

Here are two simple examples to illustrate the use of reflection. First, create a Person class:


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 for the Person class


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, through the package path of the class to get a class, in real work, is also the most used.

Example 2: object replication


@SuppressWarnings("unchecked")
public static Object copy(Object object) throws Exception {
//Gets the object type
Class classType = object.getClass();
System.out.println("" + classType.getName()); //Create a new object
with the default constructor Object objectCopy = classType.getConstructor(new Class[] {})
.newInstance(new Object[] {}); //Gets all the 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(); //Gets the name of the getXXX() method that corresponds to the property
String getMethodName = "get" + firstLetter + fieldName.substring(1); //Gets the name of the setXXX() method that corresponds to the attribute
String setMethodName = "set" + firstLetter + fieldName.substring(1); //Gets the getXXX() method that corresponds to the property
Method getMethod = classType.getMethod(getMethodName,
new Class[] {}); //Gets the corresponding setXXX() method
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 copy object
setMethod.invoke(objectCopy, new Object[] { value });
}
return objectCopy;
}

Using reflection to copy objects, we usually don't have to do this ourselves, because the open source system BeanUtils has already done the encapsulation of object copying for us, we can just call its methods directly, but it is worth noting that BeanUtils is also the encapsulation based on reflection mechanism

The following is an invocation:


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();
}


Related articles: