Two examples of JAVA using reflection

 

catalogue

1, Set a tool class and use reflection to set two methods to get and set values

1. Get the value of an attribute of an object

2. Set the value of an attribute of an object

3. Test 1: get the value of attribute

4. Test 2: set the value of the attribute

2, Upgrade

1. Method for setting the value of an attribute of an object

2. Create an object: convert map - > to object output

3. Convert a line of text -- > to map -- > call the method makeObject(date, clazz) to User object output

4. Test 1: makeObject method [make an object]  

5: Test 2: parseJsonText method

1, Set a tool class and use reflection to set two methods to get and set values

1. Get the value of an attribute of an object

public static Object getProperty(Object obj, String fieldName);

Steps:

{1} Gets the bytecode of the object

{2} Get field object

{3} Set the permissions it can access

{4} Gets the value of the field

// {1} Get the value of a property of an object
	public static Object getProperty(Object obj, String fieldName) throws NoSuchFieldException {
		// {1} Gets the bytecode of the object.
		Class class1 = obj.getClass();
		// {2} Gets the field object.
		Field f1 = class1.getDeclaredField(fieldName);
		// {3} Set the permissions it can access.
		f1.setAccessible(true);
		Object object = null;
		try {
			// {4} Gets the value of the field.
			// Format: [field]. Get (main calling object);
			object = f1.get(obj);
		} catch (IllegalArgumentException | IllegalAccessException e) {
			// {ps} these exceptions are unlikely to occur and are handled directly here.
			e.printStackTrace();
		}
		return object;
	}

2. Set the value of an attribute of an object

public static void setProperty(Object obj, String fieldName, String value);

Steps:

{1} Gets the bytecode of the object

{2} Get field object

{3} Set the permissions it can access

{4} Set the value of the field

// {2} Set the value of a property of an object
	public static void setProperty(Object obj, String fieldName, String value) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
		// {1} Gets the bytecode of the object.
		Class class1 = obj.getClass();
		// {2} Gets the field object.
		Field f1 = class1.getDeclaredField(fieldName);
		// {3} Set the permissions it can access.
		f1.setAccessible(true);
		f1.set(obj, value);

 

3. Test 1: get the value of attribute

package com.gongsi.cn.test2;

public class User {
	
	private String username;
	private String password;
	private String address;
	private String no;
	private String sex;
	private int age;
	private double weight;
	private String createDate;
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public String getNo() {
		return no;
	}
	public void setNo(String no) {
		this.no = no;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public double getWeight() {
		return weight;
	}
	public void setWeight(double weight) {
		this.weight = weight;
	}
	public String getCreateDate() {
		return createDate;
	}
	public void setCreateDate(String createDate) {
		this.createDate = createDate;
	}
	@Override
	public String toString() {
		return "User [username=" + username + ", password=" + password + ", address=" + address + ", no=" + no
				+ ", sex=" + sex + ", age=" + age + ", weight=" + weight + ", createDate=" + createDate + "]";
	}
	
}
package com.gongsi.cn.test2;

import java.util.Map;
import java.util.Scanner;

public class TestMain {

	//What are the disadvantages of {ps} traditional methods?
	//void setParameter(Map<String,Object> map){
	//	User user = new User();   // Hard coding in code
	//	user.setUsername( (String)map.get("username") );
	//	user.setPassword( (String)map.get("password") );
		//-----
	//}
	
	void setParameter(Map<String,Object> map){
		
		
	}
	
	
	public static void main(String[] args) {
		User user = new User();
		user.setAddress("Guangzhou, Guangdong");
		Scanner sc = new Scanner(System.in);
		while( true ){
			System.out.println("Please enter the property name you want to get..");
			String field = sc.nextLine();
			Object obj;
			try {
				obj = BeanUtils.getProperty(user, field);
				System.out.println( obj );
			} catch (NoSuchFieldException e) {
				System.out.println( "I'm sorry, The property you want cannot be found." );
			}
		}
	}
	
	
}

 

4. Test 2: set the value of the attribute

package com.gongsi.cn.test2;

import java.util.Scanner;

public class TestMain2 {

	public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
		User user=new User();
		//In practical application, this is not used much
		Scanner scanner =new Scanner(System.in);
		
		
		int i=1;
		while (i==1) {
			System.out.println("Please enter the properties and values to set:");
			String line=scanner.nextLine();
			if ("exit".equals(line)) {
				break;
			}
			String data[]=line.split(",");
			BeanUtils.setProperty(user, data[0], data[1]);
			
		}
		System.out.println(user);
	}
}

 

 

2, Upgrade

Three methods are set:

1. Method for setting the value of an attribute of an object

public static void setValue( Field field,Object bean, String value )

Steps:

{1} Because the string is passed in, you need to get the type of the field here

{2} Set access permissions

{3} If the value is empty, exit the method without setting

{4} Judge whether it is of String type and set it
{5} Judge whether it is of type int/Integer and set it
  {6} Judge whether it is double/Double type and set it         
  {7} Judge whether it is of float/Float type and set it
  {8} Judge whether it is of long/Long type, and set... From String to type

	//{ps} method function: set the value of an attribute of an object. 
	public static void setValue( Field field, 
		Object bean, String value ) 
		throws IllegalArgumentException
	{
		//{1} Because the string is passed in, you need to get the type of the field here
		Class type = field.getType();
		//{2} Set access permissions..
		field.setAccessible(true);
		if(value==null){  //{3} If the value is null, exit the method without setting.
			return;
		}
		try{
			//{3} Judge whether it is of String type and set it
			//{4} Judge whether it is of type int/Integer and set it
			//{5} Judge whether it is double/Double type and set it		
			//{6} Judge whether it is of float/Float type and set it
			//{7} Judge whether it is of long/Long type, and set... From String to type
			if (String.class==type) {
				field.set(bean, value);
			}if (int.class==type||Integer.class==type) {
				field.set(bean, Integer.valueOf(value));
			}if (double.class==type||Double.class==type) {
				field.set(bean, Double.valueOf(value));
			}if (float.class==type||Float.class==type) {
				field.set(bean, Float.valueOf(value));
			}if (long.class==type||Long.class==type) {
				field.set(bean, Long.valueOf(value));
			}
			}
		catch(IllegalAccessException e){
			e.printStackTrace();
		}
	}

2. Create an object: convert map - > to object output

public static <T> T makeObject(Map<String,String> data, Class<T> clazz )

Steps:

{1} Create objects based on bytecode

{2} Iterate over all the key values in the map and put the key values in the map into the Set

{3} Loop get key

{4} Get the field object according to the key. “username”

{5} Get the corresponding value according to the key. “Andy”

{6} Call setValue() to populate the property values of the object

{7} Returns an object

//{ps}makeObject method [make an object]  
    //Function: convert map - > to object output
	public static <T> T makeObject(
			Map<String,String> data, Class<T> clazz ) 
		throws InstantiationException, IllegalAccessException {
		//{1} Create objects (JavaBeans) based on bytecode
		T t = clazz.newInstance();
		//{2} Iterate over all the key values in the map and put the key values in the map into the Set
		Set<String> keySet = data.keySet();
		//Loop get key
		for (String field : keySet) {
			try {
				//{3} Get the field object according to the key. “username”
				Field f = clazz.getDeclaredField(field);
				
				//{4} Get the corresponding value according to the key. “Andy”
				String value=data.get(field);
				//{5} Call setValue() to populate the property values of the object.
				setValue(f, t, value);
			} catch (NoSuchFieldException e) {
				e.printStackTrace();
				System.out.printf("{JSON Parser}Set this field:%s",field);
			}
		}
		//{5} Returns an object
		return t;
	}

3. Convert a line of text -- > to map -- > call the method makeObject(date, clazz) to User object output


public static <T> T parseJsonText(String line, Class<T> clazz )

Steps:

{1} . a matching rule is defined

{2} Regular expression compiler processor

{3} Generate a matcher

{4} Define a HashMap to store key value pairs

{5} Repeatedly find the matching substring

{6} Store group 1 (as the key) and group 2 (as the value) into the map

{7} Call makeObject to generate objects directly

//parseJsonText method
    //Function: convert a line of text -- > to map -- > call the method makeObject(date, clazz) to User object output
		public static <T> T parseJsonText(String line, Class<T> clazz ) throws InstantiationException, IllegalAccessException {
			//{1} . a matching rule is defined
			String regex="(\"([^\"]+)\":\"([^\"]+)\")";
			//{2} Regular expression compiler processor
			Pattern patt = Pattern.compile(regex);
			//{3} Generate a matcher.
			Matcher mat = patt.matcher(line);
			//{4} Define a HashMap to store key value pairs
			Map<String, String>date=new HashMap();
			//{5} Repeatedly find the matching substring
			while (mat.find()) {
				//{6} Store group 1 (as the key) and group 2 (as the value) into the map
				date.put(mat.group(2), mat.group(3));
				
			}
			//{6} Call makeObject to generate the object directly.
		return makeObject(date, clazz);
	}

4. Test 1: makeObject method [make an object]  

package com.gongsi.cn.test3;

public class User {
	
	private String username;
	private String password;
	private String address;
	private String no;
	private String sex;
	private int age;
	private double weight;
	private String createDate;
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public String getNo() {
		return no;
	}
	public void setNo(String no) {
		this.no = no;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public double getWeight() {
		return weight;
	}
	public void setWeight(double weight) {
		this.weight = weight;
	}
	public String getCreateDate() {
		return createDate;
	}
	public void setCreateDate(String createDate) {
		this.createDate = createDate;
	}
	@Override
	public String toString() {
		return "User [username=" + username + ", password=" + password + ", address=" + address + ", no=" + no
				+ ", sex=" + sex + ", age=" + age + ", weight=" + weight + ", createDate=" + createDate + "]";
	}
	
}

 

package com.gongsi.cn.test3;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class TestMain {
	
	public static void main(String[] args) 
		throws InstantiationException, 
		IllegalAccessException,
		ClassNotFoundException {
		
		Map<String,String> data = new HashMap<>();
		data.put("username", "andy");
		data.put("password", "123");
		data.put("address", "andy");
		data.put("no", "andy");
		data.put("sex", "andy");
		data.put("age", "50");
		data.put("weight", "55.66");
		
		//{1} The key point is here.
		Scanner sc = new Scanner(System.in);
		System.out.println("Please enter where the class you need is:");
		String clsName = sc.nextLine();
		Class clazz = Class.forName( clsName );
		Object obj = JsonParser.makeObject(
						data, clazz );
		System.out.println( obj );
	}
	
	
}

 

 

5: Test 2: parseJsonText method

package com.gongsi.cn.test3;

import java.util.Scanner;
//Test the JsonParser.parseJsonText(line, clazz) method
public class TestMain2 {
	static String line = "{"+
			"\"username\":\"andy\","+
			"\"password\":\"123\","+
			"\"sex\":\"male\","+
			"\"no\":\"no01\","+
			"\"address\":\"Shenzhen, Guangdong\","+
			"\"age\":\"56\""+
			"}";
	public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		Scanner sc = new Scanner(System.in);
		System.out.println("Please enter where the class you need is:");
		String clsName = sc.nextLine();
		Class clazz=Class.forName(clsName);
		Object object=JsonParser.parseJsonText(line, clazz);
		System.out.println(object);
		
	}

}

 

Keywords: Java

Added by Kitara on Sat, 18 Sep 2021 00:28:54 +0300