Java Reflection Mechanism (i)

Source: Internet
Author: User

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


To summarize:


Reflection is a technique that allows you to get objects (classes, properties, methods) by name.


For example, we can generate an instance of a class by the class name;


You can call this method when you know the name of the method, and you can access the value of the property by knowing the name of the property.


1. Get the Class object


Use (known objects) GetClass (): Methods in the object class, each of which has this method.


such as: string str = new string ();


Class strclass = Str.getclass (); Use (class of a known subclass) Class.getsuperclass (): A method in class that returns the class of the class's parent, using (known class full name): Class.forName () static method use (known Class): Class name. class


2. Construct an instance of a class by the class name


A, call the parameterless constructor:


Class Newoneclass = Class.forName (full name); Newoneclass.newinstance ();


b, call the constructor with the parameter: we can customize a function.


Public Object newinstance (String className, object[] args) throws Exception {


Args is a parameter array


Class Newoneclass = Class.forName (className); Get the class array of the arguments (an array of class of each parameter), and decide to call that constructor class[] Argsclass = new Class[args.length]; for (int i = 0, j = args.length; I < J; i++) {Argsclass[i] = Args[i].getclass ();


}


Constructor cons = Newoneclass.getconstructor (Argsclass); Select function return cons.newinstance (args) according to Argsclass; Instantiates an object based on specific parameters.


}


3. Get the properties of an object


A, non-static property: First Get class, then get the field that this class has, and then call this field with a specific instance for the argument


public object GetProperty (object owner, String fieldName) throws Exception {Class Ownerclass = Owner.getclass ();//Get CLA First ss Field field = Ownerclass.getfield (FieldName); Then get the field that this class has, or you can get all the field Object property = Field.get (owner) by GetFields (); Owner points out that the property value of that instance is obtained, and if the property is non-public, it will be reported illegalaccessexception.


return property;


}


B, static properties:


Only the last step is different, because the static property belongs to this class, so just call this field on this class to object property = Field.get (Ownerclass);


4. Methods of executing an object


public object InvokeMethod (object owner, String methodName, object[] args) throws Exception {Class Ownerclass = Owner.get Class (); It is also the class array starting from class//To get the parameter, which is equivalent to getting an array of the type of the parameter list, depending on which function we choose.


class[] Argsclass = new Class[args.length]; for (int i = 0, j = args.length; I < J; i++) {Argsclass[i] = Args[i].getclass ();


}


Select a function based on the function name and type of functions


method = Ownerclass.getmethod (MethodName, Argsclass); Return Method.invoke (owner, args);//Specific instance, the specific parameter value is lowered with this function


}


5. Static method of executing class


Similar to the above only the last line does not need to specify a specific instance


return Method.invoke (null, args);


6. Determine if an instance of a class


public boolean isinstance (Object obj, Class cls) {return cls.isinstance (obj);


}


Test Bean class: Simplebean.java


Java code


Package Com.royzhou.bean;


public class Simplebean {


private String name;


Private string[] hobby;


Public Simplebean () {


}


Public Simplebean (String name, string[] hobby) {this.name = name; this.hobby = hobby;


}


public void SetName (String name) {


THIS.name = name;


}


Public String GetName () {


return this.name;


}


public void Sethobby (string[] hobby) {


This.hobby = hobby;


}


Public string[] Gethobby () {


return this.hobby;


}


Public String toString () {


String returnvalue = super.tostring () + "\ n"; ReturnValue + = "name:=" + this.name + "\ n"; if (this.hobby! = null) {


ReturnValue + = "hobby:";


for (String s:this.hobby) {returnvalue + = s + ",";


}


returnvalue + = "\ n";


}


Return returnvalue;


}


}


Package Com.royzhou.bean;


public class Simplebean {


private String name;


Private string[] hobby;


Public Simplebean () {


}


Public Simplebean (String name, string[] hobby) {this.name = name; this.hobby = hobby;


}


public void SetName (String name) {


THIS.name = name;


}


Public String GetName () {


return this.name;


}


public void Sethobby (string[] hobby) {


This.hobby = hobby;


}


Public string[] Gethobby () {


return this.hobby;


}


Public String toString () {


String returnvalue = super.tostring () + "\ n"; ReturnValue + = "name:=" + this.name + "\ n"; if (this.hobby! = null) {


ReturnValue + = "hobby:";


for (String s:this.hobby) {returnvalue + = s + ",";


}


returnvalue + = "\ n";


}


Return returnvalue;


}


}


Reflection Test Class: Reflecttest.java


Java code


Package Com.royzhou.bean;


Import Java.lang.reflect.Constructor; Import Java.lang.reflect.Field; Import Java.lang.reflect.Method;


public class Reflecttest {


public static void Main (string[] args) throws Exception {


Class clazz = Simplebean.class;


Instantiating a bean using the parameterless constructor


Simplebean sb = (Simplebean) clazz.newinstance (); System.out.println (SB);


Instantiating a bean using a parameter constructor


Constructor Constructor = clazz.getconstructor (new Class[]{string.class, string[].class}); SB = (Simplebean) constructor.newinstance (new object[]{"Royzhou", New string[]{"Football", "Basketball"}}); System.out.println (SB);


Set a value for the Name field


Field field = Clazz.getdeclaredfield ("name"); Field.setaccessible (TRUE); Avoid private inaccessible Throw exception Field.set (SB, "royzhou1985"); System.out.println ("Modify name using field:=" + sb.getname () + "\ n");


List all methods of class Simplebean


Method[] methods = Clazz.getdeclaredmethods (); System.out.println ("Get Methods of Class Simplebean:");


for (Method method:methods) {


if ("Sethobby". Equals (Method.getname ())) {


Dynamic invocation of a class's method to set a value for hobby


Method.invoke (SB, new object[]{new string[]{"tennis", "Fishing"}});


}


System.out.println (Method.getname ());


}


System.out.println ("\nset by Invoke Method"); System.out.println (SB);


}


}


Package Com.royzhou.bean;


Import Java.lang.reflect.Constructor; Import Java.lang.reflect.Field; Import Java.lang.reflect.Method;


public class Reflecttest {


public static void Main (string[] args) throws Exception {


Class clazz = Simplebean.class;


Instantiating a bean using the parameterless constructor


Simplebean sb = (Simplebean) clazz.newinstance (); System.out.println (SB);


Instantiating a bean using a parameter constructor


Constructor Constructor = clazz.getconstructor (new Class[]{string.class, string[].class}); SB = (Simplebean) constructor.newinstance (new object[]{"Royzhou", New string[]{"Football", "Basketball"}}); System.out.println (SB);


Set a value for the Name field


Field field = Clazz.getdeclaredfield ("name"); Field.setaccessible (TRUE); Avoid private inaccessible Throw exception Field.set (SB, "royzhou1985"); System.out.println ("Modify name using field:=" + sb.getname () + "\ n");


List all methods of class Simplebean


Method[] methods = Clazz.getdeclaredmethods (); System.out.println ("Get Methods of Class Simplebean:");


for (Method method:methods) {


if ("Sethobby". Equals (Method.getname ())) {


Dynamic invocation of a class's method to set a value for hobby


Method.invoke (SB, new object[]{new string[]{"tennis", "Fishing"}});


}


System.out.println (Method.getname ());


}


System.out.println ("\nset by Invoke Method"); System.out.println (SB);


}


}


Output Result:


[Email protected]


Name:=null


[Email protected]


Name:=royzhou


Hobby:football,basketball,


Modify name using field:=royzhou1985


Get Methods of class Simplebean:


Sethobby


Gethobby


GetName


Tostring


SetName


Set by Invoke Method


[Email protected]


name:=royzhou1985


Hobby:tennis,fishing,
...


Java Reflection Mechanism (i)

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.