The example in this article describes how Java uses reflection to automatically encapsulate entity objects. Share it with everyone for your reference. The specific analysis is as follows:
When using this method, the name of the parameter that needs to be passed must end with a row number. If the row number is removed, it is the attribute name. For example, if the page passes name+rowNo, then the attribute name of the entity object should be name. The code is as follows. Copy the code. The code is as follows: // Get page data and automatically encapsulate it into a bean object.
public List getObjectList(Class clazz,String[] rowNos) throws Exception{
List objList = new ArrayList();
for(int i=0;rowNos!=null && i<rowNos.length;i++){
//Create object instance
Object object = clazz.newInstance();
//Get the attributes declared by the class
Field[] fields = clazz.getDeclaredFields();
StringBuffer buffer = null;
//Traverse properties and perform encapsulation
for(int j=0;j<fields.length;j++){
//Get the name of the attribute
String fieldName = fields[j].getName();
//Get the name of the parameter
String paraName = fields[j].getName()+rowNos[i];
//If the obtained parameter value is empty, continue the loop
String value = getValueNull(paraName);
if(value==null){
continue;
}
//Parameter value
Object[] paramValue =new Object[1];
if(fields[j].getType().toString().equals("class java.lang.String")){
paramValue[0]=value;
}
if(fields[j].getType().toString().equals("class java.lang.Integer")){
paramValue[0]=new Integer(value);
}
if(fields[j].getType().toString().equals("class java.lang.Double")){
paramValue[0]=new Double(value);
}
if(fields[j].getType().toString().equals("class java.util.Date")){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
paramValue[0]=sdf.parse(value);
}
//Parameter type
Class[] paramType= {fields[j].getType()};
//Get the name of the set method
buffer = new StringBuffer("set");
buffer.append(fieldName.substring(0, 1).toUpperCase());
buffer.append(fieldName.substring(1));
//Get and put back
Method method = clazz.getDeclaredMethod(buffer.toString(), paramType);
//execution method
method.invoke(object,paramValue);
}
//Put the current object into the list
objList.add(object);
}
return objList;
}
I hope this article will be helpful to everyone’s Java programming.