Java Reflection mechanism

Source: Internet
Author: User

When it comes to spring, everyone will think of its core principle is ioc/di, in fact, spring implementation of Ioc/di relies on the Java reflection mechanism. Not only is spring using the reflection mechanism, Hibernate's ORM Framework is also implemented using the reflection mechanism, and the AOP dynamic agents are implemented in large numbers using reflection, so the Java reflection mechanism has been used in many of our programs. Only when we do business application development Direct use of Java reflection is less, because we do not need to reinvent the wheel, most of the application development will use some like spring, a mature framework, developers only need to provide framework configuration files. The framework allows us to focus more on business logic development, but we still need to master the implementation behind the framework in order to improve our architectural design capabilities, and perhaps we will need to develop our own frameworks or customize open source frameworks in the future.


Reflection, this word means "reflection, image, reflection," which is used in Java to refer to a classes that we can load, detect, and use completely unknown during compilation. In other words, a Java program can load a runtime to know the name of a class, learn its full construct (but not including the methods definition), and generate its object entities, or set values on its fields, or evoke its methods. This ability to "See Through Class" (the ability of the program to examine itself) is called introspection (introspection, vipassana, introspection). Reflection and introspection are the two terms that are often and are mentioned.

There must be some advantages to reflection being used extensively, and from the definition above, it can be seen that the advantages of reflection are dynamic and flexible, and everything is determined by the specific circumstances (configuration) at runtime to decide which object to create, which method to invoke, etc. This flexibility allows us to design decoupling, which is one of the best things that spring does, so we can easily replace some class files without having to recompile the related classes. Things are two-sided, reflection of course also has shortcomings, for the compile time can be determined things, the compiler can be more or less to do some optimization, and the runtime is like the interpretation of execution, the compiler is generally unable to optimize, so the use of reflection performance to take a discount, and reflection of the packaging of the class, by reflection we can access any member , including private members, which violates the principle of object-oriented design.


Java.lang.Class class: The most commonly seen class in reflection, it is the same as other Java classes, but the name happens to be called class, are inherited from the object class, in fact, it is the Java class abstract, used to describe the class metadata, such as each class has a class name, loader, hash, etc. These are the properties of the class. Class does not have a public constructor, and when Java is airborne into a class, it automatically creates an instance of the class class to represent it. For example java.lang.String, we can get a class instance by String.class, or we can get a class object by Class.forName ("Class full Name").


Some common methods of reflection:

Class C = class.forname ("ClassName"); ClassName must be the full name of Object obj = C.newinstance ();//Create Instance Constructor getconstructor (class[] params);// Gets the public constructor constructor[] GetConstructors () based on the specified parameters;//Gets all public constructor method GetMethod (String name, class[] params); Depending on the method name, the parameter type gets the public method method[] GetMethods ();//Gets all the public methods field GetField (String name);//Gets the corresponding public variable by the variable name field[ ] GetFields ();//Get the variables in the class so public


code example:

package com.stevex.app.forkjoin;import java.math.bigdecimal;public class account  implements java.io.serializable{public static final long serialversionuid =  -6928173218630110362L;private String id;private String clientId;private  Bigdecimal balance;public account () {//default constructor}public account (String id,  string clientid)  {this.id = id;this.clientid = clientid;balance =  bigdecimal.zero;} Public synchronized void withdraw (String clientid, bigdecimal amount) { Validateclient (clientId); if (Amount.compareto (balance)  < 1) {balance.subtract (amount);} Else{throw new runtimeexception ("Insufficient balance");}} Private void validateclient (String clientid)  {if (! this.clientid.equals (clientId)) { Throw new runtimeexception ("illegal Client");}} Public synchronized void depoSit (Bigdecimal amount) {if (Amount.compareto (Bigdecimal.zero)  == 1) {Balance.add (amount);} Else{throw new runtimeexception ("Overdraft not Allowed");}} Public string getclientid ()  {return clientid;} Public void setclientid (String clientid)  {this.clientid = clientid;} Public string getid ()  {return id;} Public void setid (String id)  {this.id = id;}} package com.stevex.app.forkjoin;import java.lang.reflect.constructor;import  java.lang.reflect.field;import java.lang.reflect.method;public class reflectiontest { Public static void main (String[] args)  throws classnotfoundexception, Instantiationexception, illegalaccessexception {class c = class.forname (" Com.stevex.app.forkjoin.Account "); account account =  (account)  c.newinstance (); Constructor[] cons = c.getconstructors (); MethoD[] methods = c.getmethods (); Field[] fields = c.getfields (); for (constructor con : cons) {System.out.println ( Con);} for (Method m : methods) {System.out.println (m);} for (Field f : fields) {System.out.println (f);}}}


It is interesting to find the output, even the public members that are defined in the parent class object are output.

Public com.stevex.app.forkjoin.account () Public com.stevex.app.forkjoin.account (java.lang.String, java.lang.String) Public java.lang.string com.stevex.app.forkjoin.account.getid () public  Synchronized void com.stevex.app.forkjoin.account.withdraw (Java.lang.string,java.math.bigdecimal) Public synchronized void com.stevex.app.forkjoin.account.deposit (java.math.BigDecimal) public  java.lang.string com.stevex.app.forkjoin.account.getclientid () public void  Com.stevex.app.forkjoin.Account.setClientId (java.lang.String) public void  Com.stevex.app.forkjoin.Account.setId (java.lang.String) public final void java.lang.object.wait ( )  throws java.lang.interruptedexceptionpublic final void java.lang.object.wait (Long, int)  throws java.lang.InterruptedExceptionpublic final native void  Java.lang.Object.wait (Long) &NBSP;THROWS&NBSP;JAVA.LANG.INTERRUPTEDEXCEPTIONPUBLIC&NBSp;boolean java.lang.object.equals (Java.lang.Object) public java.lang.string  Java.lang.Object.toString () Public native int java.lang.object.hashcode () public final  Native java.lang.class java.lang.object.getclass () public final native void  Java.lang.Object.notify () Public final native void java.lang.object.notifyall () public  Static final long com.stevex.app.forkjoin.account.serialversionuid


This article is from "Power from absolute love!" "Blog, be sure to keep this provenance http://stevex.blog.51cto.com/4300375/1577333

Java Reflection mechanism

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.