Java reflection reflect using __java

Source: Internet
Author: User
Tags object model reflection

The reflect class is provided in Java to help us complete the traversal of the properties of the Java class, and it can be used to complete the modification of the property. Two ways of doing this are provided in the following example:

1. Direct use of field.get and field.set operations

2. Use the Object.getclass (). GetMethod () method to obtain the getter and setter for the field, and then use Method.invoke () to implement

Examples are as follows:

Import Java.lang.reflect.Field;  
Import java.lang.reflect.InvocationTargetException;   
Import Java.lang.reflect.Method; 

Import Java.lang.reflect.Constructor; public class testjava{The public static void Reflecttest (Object model) throws Nosuchmethodexception, Illegalaccessex Ception, IllegalArgumentException, invocationtargetexception {//Get all properties of entity class, return field array field[] field = m  
		 Odel.getclass (). Getdeclaredfields ();  
				 Iterate through all properties for (int j = 0; J < Field.length; J + +) {//Get the name of the property String name = Field[j].getname ();  
				 Capitalize the first character of the property to facilitate the construction of the Get,set method name = name.substring (0, 1). toUpperCase () + name.substring (1);  
				 Gets the type of the property String type = Field[j].getgenerictype (). toString ();  
				 If type is a class type, the preceding contains "class" followed by the class name System.out.println ("property is:" + name);
				
				System.out.println ("type:" + type);  
				
					try {Class typeclass = Field[j].gettype ();
					Operates using the set and get of field. For private variables, be sure to use field. Setaccessible (True) to access field[j].setaccessible (true);
					System.out.println ("Filed Get Value is:" + field[j].get (model)); 
						if (Typeclass = = String.class) {Constructor con = typeclass.getconstructor (typeclass);
				
						Object newvalue = null;  
					NewValue = Con.newinstance ("20");
					else {Field[j].set (model, 20);
				
					System.out.println ("filed set after the value is:" + field[j].get (model));
					Use the GetMethod method to do the operation. For private variables, although you can not use Getmethod.setaccessible (true)//When you are Setmethod, be sure to call Setmethod.setaccessible (true)
					Before you can make changes.
					 Another: From the point of view of efficiency, it is recommended to call Getmethod.setaccessible (true) when GetMethod;
					 System.out.println ("method is named:" + "get" + name);
					 Method GetMethod = Model.getclass (). GetMethod ("get" + name);
					 Getmethod.setaccessible (TRUE);
					 
					System.out.println ("GetMethod value is:" + getmethod.invoke (model));
					Method Setmethod = Model.getclass (). GetMethod ("Set" + Name, Typeclass);
Setmethod.setaccessible (TRUE);					if (Type.equals ("Class java.lang.String")) {Setmethod.invoke (model, "test1");
					 else {Setmethod.invoke (model, 20);
				 System.out.println ("Set method after the value is:" + getmethod.invoke (model));
				 }catch (Exception e) {e.printstacktrace ();
			}} public static void Main (string[] args) {try {TestClass test = new TestClass (); Test.
			SetA (0); Test.
			SETB (21L); Test.
			SETC ("test");
			
			Reflecttest (test);
			System.out.println ();
			
			System.out.println ();
			TestClass2 test2 = new TestClass2 (); Test2.
			SetA (0); Test2.
			SETB (21L); Test2.
			SETC ("test");
		Reflecttest (TEST2); 
	The catch (Exception e) {}} class testclass{public int Geta () {return A;}
	public void SetA (int a) {this.a = A;}
	Public long Getb () {return B;}
	public void Setb (long b) {this.b = b;}
	Public String getc () {return C;}
	public void SetC (String c) {this.c = C;}
	Public double Gete () {return e;} public void Sete (DoubLe e) {this.e = e;}
	public float getd () {return D;}
	
	public void setd (float d) {this.d = D;}
	private int A;
	Private long B;
	Private String C;
	Private double E;
private float D; 
	Class testclass2{public Integer Geta () {return A;}
	public void SetA (Integer a) {this.a = A;}
	Public Long Getb () {return B;}
	public void Setb (Long b) {this.b = b;}
	Public String getc () {return C;}
	public void SetC (String c) {this.c = C;}
	Public Double Gete () {return e;}
	public void Sete (Double e) {this.e = e;}
	Public Float getd () {return D;}
	
	public void setd (Float d) {this.d = D;}
	Private Integer A;
	Private Long B;
	Private String C;
	Private Double E;
Private Float D; }


Although reflect provides getter and setter modifications, it is less efficient than direct access to getter and setter, so you can choose whether or not to use reflect to modify access to member properties.

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.