Java Reflection Mechanism (1)

Source: Internet
Author: User
Tags modifier idf

Reflection, at that time often listen to them, they have seen some information, but also may be used in design mode, but it does not feel a more in-depth understanding, this time to re-learn a bit, feel OK!

First, take a look at the concept of reflection:
It is the ability of a program to access, detect and modify its own state or behavior, and to adjust or modify the state and related semantics of the behavior described by the application according to the state and result of its behavior.
Reflection is a powerful tool in Java that allows us to easily create flexible code that can be assembled again at runtime without the need for source code linking between components. But the use of reflection is expensive!
Look at the concept is very faint, continue to look down.

Second, the effect of reflection mechanism:
1, decompile:. Class-->.java
2, through the reflection mechanism to access the Java object properties, methods, construction methods, etc.;
This seems to be easier to understand, and below we look at how to implement these features.

Three, let's take a look at sun. The classes in the reflection mechanism are provided for us:
Java.lang.Class;
Java.lang.reflect.Constructor; Java.lang.reflect.Field;
Java.lang.reflect.Method;
Java.lang.reflect.Modifier;

Many of the methods in reflection, attributes, and so on, we can query from these four classes. Or what sentence to learn the constant query API, that is our best teacher.

Four, the specific function realizes:
1, the reflection mechanism gets the class there are three ways to get the employee type
[Java] View plain copy print? On code to view a snippet derived from my Code slice
The first way:
CLASSC1 = Class.forName ("Employee");
The second way:
Each type in Java has a class attribute.
CLASSC2 = Employee.class;

The Third Way:
Any Java object in the Java language has a GetClass method
employeee = new Employee ();
CLASSC3 = E.getclass (); C3 is the runtime class (the run-time class for E is employee)


2, create object: Get the class later we'll create its object, using newinstance:
[Java] View plain copy print? On code to view a snippet derived from my Code slice
Class c =class.forname ("Employee");

Create a new instance of the class represented by this class object
Objecto = C.newinstance (); An employee's parameterless construction method was called.


3, gets the attribute: is divided into all attributes and the specified properties:
A, let's look at the notation for all the attributes:
[Java] View plain copy print? On code to view a snippet derived from my Code slice
Get the entire class
Class C = class.forname ("Java.lang.Integer");
Get all the properties?
field[] fs = C.getdeclaredfields ();

Defines a variable-length string used to store properties
StringBuffer sb = new StringBuffer ();
Stitching each property into this string by appending the method
The outermost public definition
Sb.append (Modifier.tostring (C.getmodifiers ()) + "class" + c.getsimplename () + "{\ n");
Each of the properties inside
for (Field Field:fs) {
Sb.append ("\ t");//Space
Sb.append (Modifier.tostring (Field.getmodifiers ()) + "");//Get modifiers for properties, such as public,static, etc.
Sb.append (Field.gettype (). Getsimplename () + "");//Name of the type of the property
Sb.append (Field.getname () + "; \ n");//property name + ENTER
}

Sb.append ("}");

System.out.println (SB);

b, get specific attributes and compare the traditional methods to learn:

[Java] view plain copy print? View the code slice to derive from my code slice
public static void Main (string[] args) throws exception{

& Lt;span style= "White-space:pre" > </span>//Previous way:
/*
User U = new user ();
U.age =//set
System.out.println (u.age);//get
*/

//Get class
Class C = Class.forName ("User");
//Get id attribute
Field idF = C.getdeclaredfield ("id");
//instantiation of this class assigns an o
Object o = c.newinstance ();
//Break Encapsulation
Idf.setaccessible (TRUE);//Use the reflection mechanism to break the encapsulation and cause the properties of the Java object to be unsafe.
//The id attribute of the O object is assigned a value of "Idf.set"
(O, "" "),//set
//get
System.out.println (Idf.get (o));
}

4, get the method, and the construction method, no longer described in detail, just look at the keyword:
Method keyword
Meaning
Getdeclaredmethods ()
Get all the methods
Getreturntype ()
Get the return type of the method
Getparametertypes ()
Get the incoming parameter type for a method
Getdeclaredmethod ("Method name", Parameter type. Class,......)
Get a specific approach


Constructor method keyword
Meaning
Getdeclaredconstructors ()
Get all the construction methods
Getdeclaredconstructor (parameter type. Class,......)
Get a specific construction method


Parent class and Parent interface
Meaning
Getsuperclass ()
Gets the parent class of a class
Getinterfaces ()
Get an interface for a class implementation

This allows us to get the various contents of the class and decompile it. For Java, which compiles and then runs the language, the reflection mechanism can make the code more flexible and easier to implement object-oriented.

Five, Reflection plus config file, make our program more flexible:
In the design mode of learning, learning the abstract factory when the reflection to more convenient reading database link string, etc., was not too understanding, then copied. Take a look. NET in the use of Reflection + configuration files:
The configuration file used at that time is the App. config file, which is in XML format and fills in the contents of the linked database:
[HTML] View plain copy print? On code to view a snippet derived from my Code slice
<configuration>
Lt;appsettings>
<add key= "" value= ""/>
Lt;/appsettings>
</configuration>

The notation of reflection:
[CSharp] View plain copy print? On code to see a snippet derived from my Code slice
Assembly.Load ("Name of the current Assembly"). CreateInstance ("Current namespace name"). The class name to instantiate);


The advantage is that it is easy for us to change the database, for example, we upgrade the system database from SQL Server to Oracle, then we write two copies of the D layer, the contents of the configuration file change, or add the conditions to choose, it brings great convenience.

Of course, the same is true in Java, except that the configuration file here is. Properties, called a property file. Reads the contents of the inside through reflection. This code is fixed, but the contents of the configuration file we can change, so that our code a lot of flexibility!

In summary, the Java reflection of the re-learning, flexible use of it, can make our code more flexible, but it also has its shortcomings, is to use it will make our software performance is reduced, complexity increases, so we also need to use it carefully.

Java Reflection Mechanism (1)

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.