Custom Tool Class (Object to Collection Map)

Posted by private_click on Sat, 21 Sep 2019 08:38:15 +0200

java obtains object attribute type, attribute name, attribute value: https://www.cnblogs.com/gmq-sh/p/5942065.html

Using java's reflection

What is the role of Class classes?

(1) Instances of Class classes represent classes and interfaces in running Java applications. One of the benefits of reflection is that it allows us to obtain type information of objects during runtime.

(2) Class has no common construction method. Class objects are automatically constructed by the Java virtual machine when loading classes and by calling the defineClass method in the class loader.  

(3) In Java, every Object has a getClass() method, through which we can get the corresponding reflection class of the object: obj.getClass().

(4) The process of loading classes is very simple: find the location of classes, load the bytecode of the Java classes found into memory, and generate the corresponding Class objects. Java class loaders are used to implement such a process.

(5) Virtual machine JVM has more than one class loader, class loader itself is a class, it also needs to be loaded into memory, so who loads these class loaders, there must be a root? Yes, there is such a root. It is the Bootstrap Class Loader, which the Dragon never sees the end.

(6) All the class libraries needed by the running environment of java are loaded by Bootstrap Class Loader, which is a program written in C++ and can run independently. It can be said to be the starting point of JVM.

(7) After Bootstrap completes its task, it generates an AppClassLoader (in fact, the system used the ExtClassLoader, which is used to load classes in the Java Runtime Environment Extension Package), which is the class loader we often use and can be obtained by calling ClassLoader.getSystemClassLoader().

(8) The area where AppClassLoader finds classes is the well-known Classspath, which we name as the Classpath class loader according to its class search scope.

(9) When new classes appear in Java, AppClassLoader first passes this class to its parent class loader, Extion ClassLoader, and asks if it can load the class. If it can, AppClassLoader will not do this. Similarly, when Extion ClassLoader loads, it will ask its parent class loader first. We can see that the class loader is actually a tree-like structure. Each class loader has its own father. When loading a class, the class loader always loads its parent loader first (how respectful to the elders). If the parent loader can't load the class, it will load it by itself, if it can't load it. Sorry, then, it will shout: Exception, class not found. It is necessary to mention that when class loading fails by directly using the classpath loader, the NoClassDefFoundException exception is thrown. If you load classes using a custom class loader loadClass method or ClassLoader's findSystemClass method, if you don't change it deliberately, you throw ClassNotFoundException.

(10) obj.getClass().getClassLoader(): Gets the class loader for the Class object.

(11) We can also call the static method forName(): Class <?> C = Class. forName ("java. lang. String");

(12) We can also use. class: Class <?> C = String. class directly.

(13) The purpose of Method Class. getMethod (String name, Class <?>... parameterTypes) is to obtain the public method declared by the object.

(14) Using reflection, we can write clearer test code, where getDeclared Methods () can get the related methods declared by the related objects themselves, while getAnnotation() can get the specified annotations of Method objects: http://www.importnew.com/24042.html

package com.Util;

import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface UserCase {
	public int id();
    public String description() default "no description";
}
package com.Util;

import java.util.List;

public class PasswordUtils {
    @UserCase(id=47, description="----Verify password format------")
    public boolean validatePassword(String password) {
        return (password.matches("\\w*\\d\\w*"));
    }
    @UserCase(id=48,description="----encryption------")
    public String encryptPassword(String password) {
        return new StringBuilder(password).reverse().toString();
    }
    @UserCase(id=49, description="------New and Old Password Verification------")
    public boolean checkForNewPassword(List<String> prevPasswords, String password) {
        return !prevPasswords.contains(password);
    }
}
package com.Util;
import com.Util.UserCase;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class UseCaseTracker {
    public static void trackUseCases(List<Integer> intList, Class<?> c) {
    	//Traversal-Reflection Method of Reflective Class of java Class
        for(Method m : c.getDeclaredMethods()) {
        	//Obtaining annotation objects through reflection classes of java classes
            UserCase uc = m.getAnnotation(UserCase.class);
            //If the comment object is not empty, print its id
            if(uc != null) {
                System.out.println("Found UserCase: " + uc.id() + " " + uc.description());
                //Remove the id of the comment object from the container
                intList.remove(new Integer(uc.id()));
            }
        }
        for(int i : intList) {
            System.out.println("warning: Defect userCase-" + i);
        }
    }
    public static void main(String[] args) {
        List<Integer> userCases = new ArrayList<Integer>();
        Collections.addAll(userCases, 47, 48, 49, 50);
        trackUseCases(userCases, PasswordUtils.class);
    }
}

 

 

 

Customize (Object to Collection Map) tool classes:

 

 

 

package com.Util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class ObjectToMapUtil {
	   
	/**
	 * getFields(): Get all the public fields of a class, including those in the parent class. 
	 * getField(String fieldName) 
	 * getDeclaredFields(): Get all declared fields of a class, that is, public, private, and protected, but not the declared fields of the parent class.
	 * getDeclaredField(String fieldName)
	*/
       public static Map<String,Object> toMap(Object obj){
    	   //New -Map
    	   Map<String,Object> m = new HashMap<String,Object>();
    	   //Get - Object Property Definition
    	   Field[] fields=obj.getClass().getDeclaredFields();
    	   //Property Definition of Loop-Object
    	   for(Field f:fields){
    		   m.put(f.getName(), getFieldValueByName(f.getName(),obj));
    	   }
    	   return m;
       }
       
       
    /**Get the attribute value according to the attribute name:
    (1)The method of obtaining the class corresponding to the object:
        Method method = XXX.getClass().getMethod(Method Name, parameter type Class <?> parameterTypes;
    (2)java The invoke method in the method class in reflection -- its function is to call the method in the XXX object:
        method.invoke(The owner object of this method is XXX, and the parameter object is Object<?>... parameterObject.
    (3)How to Get Attribute Value**/
	public static Object getFieldValueByName(String fieldName, Object obj) {
		try {
			String firstLetter = fieldName.substring(0, 1).toUpperCase();
			String getter = "get" + firstLetter + fieldName.substring(1);
			Method method = obj.getClass().getMethod(getter, new Class[] {});
			Object value = method.invoke(obj, new Object[] {});
			return value;
		} catch (Exception e) {
			System.out.println("----------Getting attribute values based on attribute names-Failure!-----------");
			return null;
		}
	}
	
	
	/*test*/
	/* String[] arg Initial parameters for running the main thread */
	public static void main(String[] arg) {
		ObjectToMapUtil.User u = new ObjectToMapUtil.User("Chang'e", "1314520");
		System.out.println("Object transformation map Result:" + ObjectToMapUtil.toMap(u).toString());
	}

	/* Static inner class */
	static class User {
		private static final long serialVersionUID = 4851912670935014257L;
		private String name;
		private String pwd;

		public User(String name, String pwd) {
			this.name = name;
			this.pwd = pwd;
		}

		public String getName() {
			return this.name;
		}

		public String getPwd() {
			return this.pwd;
		}

		public void setName(String name) {
			this.name = name;
		}

		public void setPwd(String pwd) {
			this.pwd = pwd;
		}
	}
}

Custom multi-level menu (recursion (parent-child relationship)

package com.Util;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.Entity.Permission;
import com.alibaba.fastjson.JSON;

public class RecursiveUtil {
      private List<Object> list;
      private String fieldName_For_Id_Of_Parent;//The field name of the primary key of the parent node
      private String fieldName_For_ParentId_Of_Childs;//The field name of the ParentId of the child node
      private String fieldName_For_Url_Of_Parent;//The name of the field of the parent node (used to store link addresses) or the field name of the (marked leaf node)
      //Constructor
      public RecursiveUtil(List<Object> list,
			  String fieldName_For_Id_Of_Parent,
			  String fieldName_For_ParentId_Of_Childs,
			  String fieldName_For_Url_Of_Parent){
		  this.list = list;
		  this.fieldName_For_Id_Of_Parent = fieldName_For_Id_Of_Parent;
		  this.fieldName_For_ParentId_Of_Childs = fieldName_For_ParentId_Of_Childs;
		  this.fieldName_For_Url_Of_Parent = fieldName_For_Url_Of_Parent;
      }

	  //Filter and convert List < Map < String, Object >, field Value_For_ParentId_Of_Childs to denote the value of the parent node id of the child node
      private List<Map<String,Object>> getChilds(String fieldValue_For_ParentId_Of_Childs){
    	  List<Map<String, Object>> childs = new ArrayList<Map<String,Object>>();
    	  //Find out all the children of the current parent node, put them into the new children, and return to the children
    	  for(int i=0;i<list.size();i++){
    		  if(ObjectToMapUtil.getFieldValueByName(fieldName_For_ParentId_Of_Childs, list.get(i))==fieldValue_For_ParentId_Of_Childs){
    			  childs.add(ObjectToMapUtil.toMap(list.get(i)));//Add to
    		  }
    	  }
    	  return childs;
      }
	  
      //Recursion - Map < String, Object > - {child:[{}, {}]} - callback function
      public void parentAndChildren(Map<String,Object> parent){
    	   //The end condition is a leaf node if the value corresponding to fieldName_For_Url_Of_Parent is not empty.
    	   if(null!=parent.get(fieldName_For_Url_Of_Parent))
    		   return;
    	   //Get the id of the parent node
    	   String id;
    	   //If the parameter parent content is empty and the parent node representing its child node is empty, we need to set its primary key field value to null.
    	   if(parent.isEmpty()){
    		   id = null;
    	   }else{
    	       id = (String)parent.get(fieldName_For_Id_Of_Parent);//Otherwise, get the parent's primary key value
    	   }
    	   //Traverse the list to find the child whose parent is id and place it in the property "children" of the parent
    	   List<Map<String,Object>> childsMap =getChilds(id);
    	   parent.put("childs", childsMap);
    	   for(Map<String,Object> m:childsMap){
    		   //Call yourself
    		   parentAndChildren(m);
    	   }
      }
      
      
      
      public static void main(String[] args){
    	  /**Starting time**/
    	  Date initDate = new Date();
    	  
    	  List<Object> list =new ArrayList<Object>();
    	  
    	  Permission per1=new Permission();
    	  per1.setId("1");
    	  per1.setName("system management");
    	  
    	  Permission per11=new Permission();
    	  per11.setId("11");
    	  per11.setName("user management");
    	  per11.setParentid("1");
    	  
    	  Permission per111=new Permission();
    	  per111.setId("111");
    	  per111.setName("customer management");
    	  per111.setUrl("userManager");
    	  per111.setParentid("11");
    	  
    	  
    	  Permission per112=new Permission();
    	  per112.setId("112");
    	  per112.setName("Administrator Management");
    	  per112.setUrl("sysUserManager");
    	  per112.setParentid("11");

    	  
    	  list.add(per1);
    	  list.add(per11);
    	  list.add(per111);
    	  list.add(per112);
    	  
    	  //Create a RecursiveUtil object
    	  RecursiveUtil  rec = new RecursiveUtil(list,"id","parentid","url");
    	  //Create a new result object result
    	  Map<String,Object> result=new HashMap<String,Object>();
    	  //Processing result through callback function parentAndChildren(result)
    	  rec.parentAndChildren(result);
    	  //Convert json. to JSONString (Object obj) calling fastJson package into json format
    	  System.out.println(JSON.toJSONString(result));
    	  
    	  /**End time**/
    	  Date endDate = new Date();
    	  //Time interval (in microseconds)
    	  long microSecondInterval = (endDate.getTime() - initDate.getTime());
    	  //Time interval (in seconds)
    	  double SecondInterval =((double)microSecondInterval)/1000;
    	  System.out.println("Running time interval:"+SecondInterval+"second");
      }
}

 

Topics: Java Attribute JSON jvm