Thinking of Java Reflection

Source: Internet
Author: User

The so-called reflection, in the runtime state, gets the properties and methods in the class, as well as a mechanism for invoking the methods therein. The purpose of this mechanism is to obtain the classes (Class) and the properties (Field), methods, and methods in which the runtime knows, as well as to set the property values in them. The most important step in implementing reflection in Java, and the first step is to get the class object, which allows you to call the appropriate method to get the properties, methods, and methods in the class from that object. There are several implementations of reflection in Java: 1. You can get the class object represented by the string by loading the string with the Class.forName () method. For example:class<?> clazz = Class.forName ("java.lang.String") you can get the class object of the String class. It is worth noting that the string must be the full name of the class, that is, the package name + class name. The code below is the configuration of an action in the Struts configuration file struts.xml.
<action name= "Registe" class= "cn.com.huixin.struts2.RegisteAction" >    <result   >/registeResult.jsp</result>  <result name= "Input" >/registe2.jsp</ Result></action>
The Class property here gives a string of the full name of a class, and how does the server get the class object from this string? is to registeaction objects through the reflection mechanism. Then call the default execute () method in this class. 2. The class object is obtained by calling the classes property through the name For example:class<?> Clazz = String.class can also get the class object of the String class. 3. Call the GetClass () method of the instance. For example: date date = new Date ();
Class<?> clazz = Date.getclass (); The class object of the date instance can be obtained by two lines of code above.

1 getting the reflected object
Package Com.qianfeng.reflect;import com.qianfeng.domain.person;/* Reflection: Get a member of a class or class dynamically, and use a class or member of a class to get a class bytecode file object in a way ( Class name of the. Class) */public class ReflectDemo1 {public ReflectDemo1 () {//TODO auto-generated constructor stub}public static void M          Ain (string[] args) throws ClassNotFoundException {//get1 ();//get2 (); Get3 ();} private static void Get3 () throws ClassNotFoundException {//The byte-code file object is obtained by name in string form, no object is required, and class classes Claz = Class.forName ( "Com.qianfeng.domain.Person"); System.out.println (Claz);} private static void Get2 () {//Each data type has a class attribute that can be used by the class to get the bytecode file object of the class it belongs to//does not need the object, but requires class Claz = Person.class; Class claz2 = Person.class; System.out.println (CLAZ==CLAZ2);} private static void Get1 () {//mode one: Gets the byte-code file object of the owning class by object//either object has the bytecode file object of its owning class//new person () person.class//features: This way you need to create the object person p1 = new person (); Class claz1 = P1.getclass ();//person.classperson P2 = new Person (); Class claz2 = P2.getclass ();//person.classsystem.out.println (CLAZ1==CLAZ2);}}

2   How to get objects that are reflected
Package Com.qianfeng.reflect;import Java.lang.reflect.constructor;import Java.lang.reflect.invocationtargetexception;import Com.qianfeng.domain.person;public class ReflectDemo2 {/** * @  param args * @throws classnotfoundexception * @throws illegalaccessexception * @throws instantiationexception * @throws SecurityException * @throws nosuchmethodexception * @throws invocationtargetexception * @throws Illegalargumentexcepti On */public static void main (string[] args) throws ClassNotFoundException, Instantiationexception, Illegalaccessexception, Nosuchmethodexception, SecurityException, IllegalArgumentException, InvocationTargetException {//dynamically Gets the class and creates the object Createobj (); CreateObj2 ();} private static void CreateObj2 () throws ClassNotFoundException, Nosuchmethodexception, SecurityException, Instantiationexception, Illegalaccessexception, IllegalArgumentException, invocationtargetexception {//Dynamic get class string Str= "Com.qianfeng.domain.Person"; Class Claz = Class.forName (str);//int.class;//with parametersConstruction method to create the object//first to get the construction method with parameters//person P = new Person ("LSDJKF");//string.class int.classconstructor con = Claz.getconstructor (String.class,int.class);//Use the obtained constructor method to create the object obj = Con.newinstance ("John Doe", 29);// Call the Newinstance () method System.out.println (obj) of the constructor method object;} private static void Createobj () throws ClassNotFoundException, Instantiationexception, illegalaccessexception {// Person p = new person ();//1 load Person.class 2: Open Memory 3: Construct method//Dynamic Get class string str= "Com.qianfeng.domain.Person"; Class Claz = Class.forName (str);//Create Object obj = Claz.newinstance ();//Call this byte-code file Object Newinstance () Method System.out.println (obj);}}

3 getting member variables in an object
Package Com.qianfeng.reflect;import Java.lang.reflect.field;public class ReflectDemo3 {/** * @param args * @throws classn  Otfoundexception * @throws SecurityException * @throws nosuchfieldexception * @throws illegalaccessexception * @throws Instantiationexception */public static void Main (string[] args) throws ClassNotFoundException, Nosuchfieldexception, Se Curityexception, Instantiationexception, illegalaccessexception {///dynamically gets the class and after creating the object, accesses the member property Accessfield ();} private static void Accessfield () throws ClassNotFoundException, Nosuchfieldexception, SecurityException, Instantiationexception, illegalaccessexception {//person p = new Person ();//p.name = "";//Dynamic Get class string str= " Com.qianfeng.domain.Person "; Class Claz = Class.forName (str);//Gets the field//field f = Claz.getfield ("name");//The field that can only get permission to be public fields F = Claz.getdeclaredfield ("name");//system.out.println (f);//Assign a value to a field-you need an object first//create object obj = Claz.newinstance ();// Set permissions to accessible f.setaccessible (TRUE);//force access//Assign value to field F.set (obj, "Floret"); System.out.println (obj);}} 

4 Getting the methods in an object
Package Com.qianfeng.reflect;import Java.lang.reflect.invocationtargetexception;import Java.lang.reflect.Method; public class ReflectDemo4 {/** * @param args * @throws classnotfoundexception * @throws SecurityException * @throws Nosu Chmethodexception * @throws invocationtargetexception * @throws illegalargumentexception * @throws Illegalaccessexcepti On * @throws instantiationexception */public static void Main (string[] args) throws ClassNotFoundException, Nosuchmethod Exception, SecurityException, Instantiationexception, Illegalaccessexception, IllegalArgumentException, InvocationTargetException {//dynamically Gets the class and creates the object, accesses the member Method//accessmethod (); AccessMethod1 (); AccessMethod2 ();} private static void AccessMethod2 () throws Nosuchmethodexception, SecurityException, ClassNotFoundException, Illegalaccessexception, IllegalArgumentException, invocationtargetexception {//Dynamic get class String str= "    Com.qianfeng.domain.Person ";        Class Claz = Class.forName (str); Method m = Claz.getmethod ("meth", null); M.invoke (null,null);} Get the method with parameters and execute private static void AccessMethod1 () throws ClassNotFoundException, Nosuchmethodexception, securityexcept Ion, Instantiationexception, Illegalaccessexception, IllegalArgumentException, invocationtargetexception {//Dynamic get class S    Tring str= "Com.qianfeng.domain.Person";        Class Claz = Class.forName (str);        Method m = Claz.getmethod ("func", String.class);        Object obj = claz.newinstance ();    M.invoke (obj, "haha"); }//gets the method without parameters and executes the private static void Accessmethod () throws ClassNotFoundException, Nosuchmethodexception, SecurityException, Instantiationexception, Illegalaccessexception, IllegalArgumentException, InvocationTargetException {//Dynamically get class string str= "Com.qianfeng.domain.Person"; Class Claz = Class.forName (str); Method m = Claz.getmethod ("show", null);//Create Object obj = Claz.newinstance (); M.invoke (Obj,null);}}




Thinking of Java Reflection

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.