Java Basics JVM-—— use reflection to build and manipulate objects

Source: Internet
Author: User

Class objects can get methods in the class, represented by the method object, invoke the method's invoke can execute corresponding methods; You can get the constructor, which is represented by the constructor object. Call the Newinstance method of the constructor object to execute the constructor of the class, and you can get the member variable, represented by the Field object, which can directly modify the access rights and values of the member variables of the class.

Creating objects

Objects are created in two ways through reflection

Using the Class object's newinstance (), this is the most common way to create objects based on profile information.

Gets the specified constructor object by using the class object, and then creates an object of the class from the newinstance of the constructor object.

Calling methods

The first thing to do is to get the class object in the JVM, to get the method of class by the GetMethod method of class object, return the object of method type, and finally execute the method of class by Invoke of method object.

The following example demonstrates reading data from a configuration file to create an object dynamically, and also initializes the object with configuration file information to execute the object's setter.

1  Packagejvmtest;2 3 ImportJava.io.FileInputStream;4 Importjava.io.IOException;5 ImportJava.lang.reflect.Method;6 ImportJava.util.HashMap;7 ImportJava.util.Map;8 Importjava.util.Properties;9 Ten  Public classExtendedobjectpoolfactory { One     Privatemap<string, object> Objectpool =NewHashmap<>(); A     PrivateProperties config =NewProperties (); -      Public voidInit (String fileName) { -         Try { theFileInputStream FIS =NewFileInputStream (fileName); - config.load (FIS); -}Catch(IOException ex) { -System.out.println ("read" + fileName + "Exception"); + ex.printstacktrace (); -         } +     } A     PrivateObject CreateObject (String Clazzname)throwsException { at         class<?> clazz = Class.forName (clazzname); -         //To create an object using the Clazz default constructor -         return clazz.newinstance (); -     } -     //to create an object from a configuration file -      Public voidInitpool ()throwsException { in          for(String name:config.stringPropertyNames ()) { -             if(!name.contains ("%")) { to Objectpool.put (Name, CreateObject (Config.getproperty (name))); +             } -         } the     } *      $     //performs the set method of the object corresponding to the configuration filePanax Notoginseng      Public voidInitproperty ()throwsException { -          for(String name:config.stringPropertyNames ()) { the             if(Name.contains ("%")) { +string[] Objandpro = name.split ("%"); A                 //Get Object theObject target = GetObject (objandpro[0]); +                 //Construct Setter Method name -String mtdname = "Set" + objandpro[1].substring (0,1). toUpperCase () + objandpro[1].substring (1); $                 class<?> targetclass = Target.getclass (); $                 Method MTD = Targetclass.getmethod (Mtdname, string.class); - Mtd.invoke (Target, Config.getproperty (name)); -             } the         } -     }Wuyi      the      PublicObject getObject (String name) { -         returnobjectpool.get (name); Wu     } -      About      Public Static voidMain (string[] args)throwsException { $Extendedobjectpoolfactory EPF =Newextendedobjectpoolfactory (); -Epf.init ("ExtObj.txt"); - Epf.initpool (); - Epf.initproperty (); ASystem.out.println (Epf.getobject ("a")); +     } the}

The object is dynamically created on line 25th using the default constructor, after the 23rd line of the program gets the class object.

If you want to use the specified constructor, you need to get the constructor object first, and then create the object using the newinstance of the Cronstructor object, like so,

1 Constructor ctor = Clazz.getconstructor (String.  Class); 2 return ctor.newinstance ("Here are parameter for specific constructor");

Line 45th Gets the class object, in line 46 gets the specified method (with a parameter) from the class object, represented by the method object, and the invoke of the method object in the last 47 rows can execute the specified method of the class.

The example above is tested using the following test file,

ExtObj.txt

1 a=javax.swing.JFrame2 b=javax.swing.JLabel3 a%title=test title

Input results,

Javax.swing.jframe[frame0,0,0,0x0,invalid,hidden,layout=java.awt.borderlayout,title=test Title,resizable,normal , defaultcloseoperation=hide_on_close,rootpane=javax.swing.jrootpane[,0,0,0x0,invalid,layout= Javax.swing.jrootpane$rootlayout,alignmentx=0.0,alignmenty=0.0,border=,flags=16777673,maximumsize=,minimumsize =,preferredsize=],rootpanecheckingenabled=true]
View CodeAccessing member variables

The specified member variable can be accessed through the GetField method of the class object, and calls to the Setaccessable method that inherit from Accessableobject can gain access to the private member variable.

The following methods can access member variables,

Get (Object obj), which gets the value of the member variable. If it is a base type, use the GetInt (object obj) directly, GetChar (object obj) in a way

Set (Object obj), which sets the value of the member variable. If it is a base type, use the same way as Setint (object, int val), SetChar (object obj, char c)

The following shows the access member variables,

1  Packagejvmtest;2 3 ImportJava.lang.reflect.Field;4 5 classPerson {6     PrivateString name;7     Private intAge ;8      PublicString toString () {9         return"Person[name:" +name+ ", Age:" +age+ "]";Ten     } One } A  Public classFieldtest { -      Public Static voidMain (string[] args)throwsException { -Person p =NewPerson (); theclass<person> clazz = person.class; -         //getdeclaredfiled member variables that can get all access rights -Field NameField = Clazz.getdeclaredfield ("name"); -         //true to remove permission restrictions +Namefield.setaccessible (true); -         Namefield.set (P, "Tom"); +Field Agefield = Clazz.getdeclaredfield ("Age"); AAgefield.setaccessible (true); at         Agefield.setint (P, +); - System.out.println (p); -     } -}

The above program line 20th uses set (), and 23 rows use Setint (), Output,

Person[name:tom, Age:18]
manipulating arrays

Java.lang.reflect also contains an array class that dynamically creates an array, sets the value of the element, and is more powerful, the main method being,

Newinstance (..), create an array, you can specify the array element type, the array dimension, the length of the array

Get (...), get the element indexed as index, for an array of base data types, by Getint (...), GetChar (...) ...

Set (...), sets the element indexed to index, for an array of base data types, by Setint (...), SetChar (...) ...

The following demonstrates usage,

1  Packagejvmtest;2 3 ImportJava.lang.reflect.Array;4 5  Public classArrayTest2 {6      Public Static voidMain (string[] args) {7         //Create a three-dimensional array8Object arr = array.newinstance (String.class, 3, 4, 10);9         //gets the element with index 2, which is a two-dimensional arrayTenObject arrobj = Array.get (arr, 2); One         //assigns a value to an element with a two-dimensional array index of 2 A         //the elements of a two-dimensional array are one-dimensional arrays, so assignments are also assigned values using arrays -Array.set (Arrobj, 2,NewString[] {"King of the Land Tiger", "Pagoda Town River Demon" }); -         //gets a two-dimensional array that specifies the element of index (the result is a one-dimensional array) theObject Anarr = Array.get (Arrobj, 3); -Array.set (Anarr, 8, "pheasant bulkhead drill, where to mount Uranus"); -         //To cast arr to a three-dimensional array -string[][][] Cast =(string[][][]) arr; +          -System.out.println (cast[2][2][0]); +System.out.println (cast[2][2][1]); ASystem.out.println (cast[2][3][8]); at     } -}

The output is as follows,

1 King cover the ground tiger 2 Pagoda Town River Demon 3 Pheasant in the hole, where to Mount Uranus

Java Basics JVM-—— use reflection to build and manipulate objects

Related Article

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.