A brief analysis of Java Reflection Mechanism (Reflection) _java

Source: Internet
Author: User
Tags object serialization

Reflection, a reflection, is an important feature of the Java language, we know that before we use a class, we tend to create it, such as creating a class file and then writing properties, methods, and so on, which is static, but the reflection mechanism allows you to create a class dynamically. In addition to dynamically creating a class, we are able to dynamically retrieve the data of the same object and assign it to the newly created class, which is somewhat similar to cloning replication. In many cases, we all need the characteristics of this dynamically created class, for example, in dealing with some business, but these businesses are slightly different, often corresponding to a number of classes, in processing, we will be based on different business processes to invoke different classes, this time the reflection mechanism to come in handy.

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

Provides classes and interfaces to get reflection information about classes and objects. Within the security restrictions, reflection allows programmatic access to information about the fields, methods, and construction methods of the load class, and allows the use of reflection fields, methods, and construction methods to manipulate the underlying peers on the object.

If the required reflectpermission is available, AccessibleObject allows the access check to be suppressed.

Arrays provides static methods for dynamically creating and accessing arrays.

The classes and Java.lang.Class in this package can be adapted to the needs of the following applications: debugger, interpreter, Object Checker, class viewer, and services (for example, object serialization and JavaBean, They need to access the public members of the target object (based on its Run-time class) or the members of a given class declaration.

Here are two simple examples to illustrate the use of reflection, first by creating a person class:

Copy 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 property and method information of the person class

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

Instance 2: Object replication

Copy Code code as follows:

@SuppressWarnings ("Unchecked")
public static object Copy (object) throws Exception {
Get Object Type
Class ClassType = Object.getclass ();
System.out.println ("" + Classtype.getname ()); Create a new object by using the default construction method
Object objectcopy = Classtype.getconstructor (new class[] {})
. newinstance (New object[] {}); Get all the properties of an 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 attribute
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); 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 ()}); Invoke the GetXXX () method of the original object
Object value = Getmethod.invoke (object, new object[] {});
System.out.println (FieldName + ":" + value); Invoke the Setxxx () method of the copied object
Setmethod.invoke (Objectcopy, new object[] {value});
}
return objectcopy;
}

Using reflection to replicate objects, we don't usually do this ourselves, because the open source system Beanutils has already encapsulated the object copy for us, we call it directly, but it's worth noting that Beanutils is also based on the reflection mechanism of the encapsulation

Here is a call to:

Copy Code code as follows:

public static void Main (string[] args) {
person who = 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 Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.