A brief analysis of Java reflection mechanism

Source: Internet
Author: User

The Java reflection mechanism is in the running state, for any class, can know all the properties and methods of this class, for any one object, can call any of its methods and properties; This dynamically acquired information and the ability to dynamically invoke the object's methods are called the reflection mechanisms of the Java language.

"When a program is run, it allows you to change the program structure or variable type, which is called Dynamic language." From this point of view, Perl,python,ruby is a dynamic language, and c++,java,c# is not a dynamic language. But Java has a very prominent dynamic-related mechanism: Reflection, in Java, refers to the classes that we can load, detect, and use completely unknown during compilation at runtime. 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.

The main related classes of the Java reflection mechanism are:
Java.lang.Class;
Java.lang.reflect.Constructor;
Java.lang.reflect.Field;
Java.lang.reflect.Method;
Java.lang.reflect.Modifier;

There are three ways to get class in Java (Take the Userbean class as an example):
1. Class name
Userbean.class
2. Object. GetClass ();
UserBean UserBean = new UserBean ();
Userbean.getclass ();
3, Class.forName ()
Class.forName ("Com.alfred.bean.UserBean");
If you do not add a path in the sibling directory

One thing to explain is that everything in Java is an object, and the class we get is also an object. The base type int, float, etc. also generate a class object in the JVM's memory pool like other types. Combined data types, such as arrays, generate a class object, and, more surprisingly, the true nature of an array in Java is a class.
For example:
Class C1 = Int.class;
Class C2 = Double[].class;

By using the Java reflection mechanism, you can implement:
1. Run-Time Get class structure (including class name, modifier, property, method, constructor, parent class, interface, etc.)
2. Call the class public method at runtime (can pass method parameters)
3. Creating class objects at run time

The following is an example of a Java reflection mechanism:

 PackageCom.alfred.main;ImportJava.lang.reflect.Array;ImportJava.lang.reflect.Constructor;ImportJava.lang.reflect.Field;ImportJava.lang.reflect.Method;ImportJava.lang.reflect.Modifier; Public classReflection {/*** Print the entire class structure (including parent-child class interface) *@paramC Class Object*/     Public Static voidprintclassstructure (Class c) {Try {            //get all properties (excluding parent class)field[] fs =C.getdeclaredfields (); //defines a variable-length string used to store propertiesStringBuffer SB =NewStringBuffer (); //stitching each property into this string by appending the method//the outermost public definitionSb.append (Modifier.tostring (C.getmodifiers ()) + "class" +c.getsimplename ()); Class Superclass=C.getsuperclass (); if(Superclass! =NULL&&!superclass.getsimplename (). Equals ("Object")) {                //does not directly inherit from object, indicating that there are other inheriting classesprintclassstructure (superclass); Sb.append ("Extends" +superclass.getsimplename ()); } class[] Interfaces=c.getinterfaces (); if(Interfaces.length > 0) {sb.append ("Implements");  for(inti = 0; i < interfaces.length; i++) {printclassstructure (interfaces[i]); Sb.append (((I! = 0)? "," : "")                            +interfaces[i].getsimplename ()); }} sb.append ("{\ n"); //properties in a class             for(Field field:fs) {sb.append ("\ t");//Indent inSb.append (Modifier.tostring (Field.getmodifiers ()) + "");//gets the modifier for the property, such as Public,static, and so onSb.append (Field.gettype (). Getsimplename () + ""); Sb.append (Field.getname ()+ "; \ n"); }            //constructing methods in a classconstructor[] Declaredconstructors =c.getdeclaredconstructors ();  for(Constructor constructor:declaredconstructors) {sb.append ("\ T"); Sb.append (Modifier.tostring (Constructor.getmodifiers ())+ " "); Sb.append (C.getsimplename ()+ "("); Class[] Parametertypes=constructor.getparametertypes ();  for(inti = 0; i < parametertypes.length; i++) {Sb.append (((I! = 0)? "," : "")                            + parametertypes[i].getsimplename () + "arg" +i); } sb.append (") {}\n")); }            //methods in a classMethod[] ms =C.getdeclaredmethods ();  for(Method method:ms) {sb.append ("\ T"); Sb.append (Modifier.tostring (Method.getmodifiers ())+ " "); Sb.append (Method.getreturntype (). Getsimplename ()+ " "); Sb.append (Method.getname ()+ "("); Class<?>[] Parametertypes =method.getparametertypes ();  for(inti = 0; i < parametertypes.length; i++) {Sb.append (((I! = 0)? "," : "")                            + parametertypes[i].getsimplename () + "arg" +i); } sb.append (") {}\n")); } sb.append ("}");            System.out.println (SB); System.out.println ("================================="); } Catch(Exception e) {e.printstacktrace (); }    }    /*** Get the public properties of an object *@paramowner *@paramFieldName *@returnthe Property Object *@throwsException*/     Public StaticObject GetProperty (object owner, String fieldName)throwsException {Class Ownerclass=Owner.getclass (); Field field=Ownerclass.getdeclaredfield (fieldName); Object Property=Field.get (owner); returnProperty ; }    /*** Get static public properties of a class *@paramClassName class name *@paramFieldName Property name *@returnthe Property Object *@throwsException*/     Public StaticObject Getstaticproperty (String className, string fieldName)throwsException {Class Ownerclass=Class.forName (className); Field field=Ownerclass.getfield (fieldName); Object Property=Field.get (Ownerclass); returnProperty ; }    /*** Execute an object method *@paramOwner Object *@paramMethodName Method Name *@paramargs parameter *@returnmethod return value *@throwsException*/     Public StaticObject InvokeMethod (object owner, String methodName, object[] args)throwsException {Class Ownerclass=Owner.getclass (); Class[] Argsclass=NewClass[args.length];  for(inti = 0, j = args.length; I < J; i++) {Argsclass[i]=Args[i].getclass (); } Method=Ownerclass.getmethod (MethodName, Argsclass); returnMethod.invoke (owner, args); }    /*** Perform a static method of a class *@paramClassName class name *@paramMethodName Method Name *@paramargs parameter array *@returnresults returned by the execution method *@throwsException*/     Public StaticObject Invokestaticmethod (String className, String methodName, object[] args)throwsException {Class Ownerclass=Class.forName (className); Class[] Argsclass=NewClass[args.length];  for(inti = 0, j = args.length; I < J; i++) {Argsclass[i]=Args[i].getclass (); } Method=Ownerclass.getmethod (MethodName, Argsclass); returnMethod.invoke (NULL, args); }    /*** NEW instance *@paramClassName class name *@paramparameters of the args constructor *@returnnew instance *@throwsException*/     Public StaticObject newinstance (String className, object[] args)throwsException {Class Newclass=Class.forName (className); Class[] Argsclass=NewClass[args.length];  for(inti = 0, j = args.length; I < J; i++) {Argsclass[i]=Args[i].getclass (); } Constructor Cons=Newclass.getconstructor (Argsclass); returncons.newinstance (args); }    /*** is not an instance of a class *@paramobj Instance *@paramCLS class *@returnreturns True if obj is an instance of this class*/     Public Static Booleanisinstance (Object obj, Class cls) {returncls.isinstance (obj); }    /*** Get an element in the array *@paramArray Arrays *@paramIndex Indices *@returnreturns the value of the index component in the specified array object*/     Public StaticObject Getbyarray (Object array,intindex) {        returnarray.get (Array, index); }}

A brief analysis of 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.