Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is cascading object instantiation

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "what is the instantiation of cascading objects". The content of the explanation in the article is simple and clear, and it is easy to learn and understand. let's study and learn "what is cascading object instantiation"!

Cascading object instantiation

If there is a cascading relationship with other references in a given class object, it is called a multi-level setting. For example, an employee belongs to a department and a part belongs to a company, so the basic relationship for a simple Java class is defined as follows:

Company:

Class Company {private String name;private Date createdate;}

Dept:

Class Dept {private String dname;private String loc;private Company company;}

Emp:

Class Emp {private Long empno;private String ename;private String job;private double salary;private Date hireDate;private Dept dept;}

If you want to operate through Emp, you should use "." As a cascading relationship:

Dept.dname: finance Department Emp class instantiation object .getDept (). SetDname ("Finance Department") dept.company.name:MLDNEmp class instantiation object. GetDept ().. getCompany (). SetName ("MLDN")

Considering the simplicity of the code, you should consider that you can automatically instantiate properties in a class through a cascading configuration.

String value= "empno:7369 | ename:Smith | job:Clerk | salary:750.00 | hiredate:1989-10-10" + "dept.dname: finance Department | dept.company.name:MLDN"

At present, there is a multi-level relationship between attributes, so the multi-level relationship must be distinguished from the single-level configuration.

Import java.lang.reflect.Field;import java.lang.reflect.Method;public class JavaAPIDemo {public static void main (String [] args) throws Exception {String value= "empno:7369 | ename:Smith | job:Clerk | salary:750.00 | hiredate:1989-10-10" + "dept.dname: finance Department | dept.company.name:MLDN"; Emp emp = ClassInstanceFactory.create (Emp.class, value) System.out.println ("employee number:" + emp.getEmpno () + ", name:" + emp.getEname () + ", position:" + emp.getJob () + ", basic salary:" + emp.getSalary () + ", date of employment:" + emp.getHiredate ()); System.out.println (emp.getDept ()); System.out.println (emp.getDept (). GetCompany () }} class ClassInstanceFactory {private ClassInstanceFactory () {} / * instantiate the creation method of the object, which can be based on the passed string structure: "attribute: content | property: content" * @ param clazz reflects the Class object to be instantiated With Class, you can reflect the property content of the instantiated object * @ param value to be set to the object * @ return A Java object that has been configured with property content * / public static T create (Class clazz,String value) {/ / if you want to use reflection for simple Java class object property settings, the class must have a nonparametric construct try {Object obj = clazz.getDeclaredConstructor (). NewInstance () BeanUtils.setValue (); / / set the property return (T) obj; / / return object} catch (Exception e) {e.printStackTrace (); / / if an error really occurs at this time, essentially return null;} class StringUtils {public static String initcap (String str) {if (str = = null | | ".equals (str)) {return str } if (str.length () = = 1) {return str.toUpperCase ();} else {return str.substring (0,1) .toUpperCase () + str.substring (1) } class BeanUtils {/ / Bean-processed class private BeanUtils () {} / * implements the property setting of the specified object * @ param obj the instantiated object to be reflected * @ param value contains the string of the specified content Format "attribute: content | attribute: content" * / public static void setValue (Object obj,String value) {String results [] = value.split ("\\ |") / / split for for each set of attributes according to "|" (int x = 0; x

< results.length; x ++) { //循环设置属性内容//attval [0]保存的是属性名称,attval [1]保存的是属性内容String attval [] = results[x].split(":"); //获取"属性名称"和内容try {if (attval[0].contains(".")) { //多级配置String temp [] = attval[0].split("\\."); Object currentObject = obj;// 最后一位肯定是指定类中的属性名称,所以不在本次实例化处理的范畴之内for (int y = 0 ; y < temp.length - 1 ; y ++) { // 实例化// 调用了相应的getter方法,如果getter方法返回了null,表示该对象未实例化Method getMethod = obj.getClass().getDeclaredMethod("get" + StringUtils.initcap(temp[y])); Object tempObject = getMethod.invoke(currentObject); if (tempObject == null) { //该对象现在并没有实例化Field field = currentObject.getClass().getDeclaredField(temp[y]); //获取属性类型Method method = currentObject.getClass().getDeclaredMethod("set" + StringUtils.initcap(temp[y]), field.getType()); Object newObject = field.getType().getDeclaredConstructor().newInstance(); method.invoke(currentObject, newObject); currentObject = newObject; }else { currentObject = tempObject; } System.out.println(temp[y] + "--" + currentObject); } }else { Field field = obj.getClass().getDeclaredField(attval[0]); //获取成员Method setMethod = obj.getClass().getDeclaredMethod("set" + StringUtils.initcap(attval [0]), field.getType()); Object convertValue = BeanUtils.convertAttributeValue(field.getType().getName(), attval[1]); setMethod.invoke(obj, convertValue); //调用setter方法设置内容} }catch (Exception e) {} } }/** * 实现属性类型转换处理 * @param type 属性类型,通过Field获取 * @param value 属性的内容,传入的都是字符串,需要将其变为指定类型 * @return 转换后的数据类型 */private static Object convertAttributeValue(String type, String value) {if ("long".equals(type) || "java.lang.Long".equals(type)) { //长整型return Long.parseLong(value); }else if ("int".equals(type) || "java.lang.int".equals(type)) {return Integer.parseInt(value); }else if ("double".equals(type) || "java.lang.double".equals(type)) {return Integer.parseDouble(value); }else if ("java.util.Date".equals(type)) { SimpleDateFormat sdf = null;if (value.matches("\\d{4}-\\d{2}-\\d{2}") { //日期类型sdf = new SimpleDateFormat("yyyy-MM-dd"); } else if (value.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}") { sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); }else {return new Date() ; //当前日期}try {return sdf.parse(value); } catch(ParseException e) {return new Date() ; //当前日期} }else {return value; } }}class Company{private String name;private Date createdate;public String getName() {return name; }public void setname(String name) {this.name = name; } public Date getCreatedate() {return createdate; }public void setCreatedate(Date createdate) {this.createdate = createdate; } }class Dept{private String dname;private String loc;private Company company;public String getDname() {return dname; }public void setDname(String dname) {this.dname = dname; } public String getLoc() {return loc; }public void setLoc(String loc) {this.loc = loc; } public Company getCompany() {return company; }public void setCompany(Company company) {this.company = company; } }class Emp{private long empno;private String ename;private String job;private double salary;private Date hiredate;private Dept dept;public Dept getDept() {return dept; }public void setDept(Dept dept) {this.dept = dept; }public void setEname(String ename) {this.ename = ename; }public void setJob(String job) {this.job = job; }public String getEname() {return ename; }public String getJob() {return job; }public long getEmpno() {return empno; }public void setEmpno(Long empno) {this.empno = empno; }public double getSalary() {return salary; }public void setSalary(double salary) {this.salary = salary; }public Date getHiredate() {return hiredate; }public void setHiredate(Date hiredate) {this.hiredate = hiredate; }}

The instantiation of these automatic cascading configurations is bound to be used in future project writing.

Cascading property settin

Now that you have successfully implemented the cascading object instantiation processing, then you need to consider the setting of the cascading properties. Before considering the cascading object instantiation processing, there is one bit missing in the loop.

For (int y = 0; y < temp.length-1; y + +) {/ / instantiates / / calls the corresponding getter method. If the getter method returns null, it means that the object is not instantiated Method getMethod = obj.getClass (). GetDeclaredMethod ("get" + StringUtils.initcap (temp [y])); Object tempObject = getMethod.invoke (currentObject) If (tempObject = = null) {/ / the object is not now instantiated Field field = currentObject.getClass (). GetDeclaredField (temp [y]); / / get attribute type Method method = currentObject.getClass (). GetDeclaredMethod ("set" + StringUtils.initcap (temp [y]), field.getType ()); Object newObject = field.getType (). GetDeclaredConstructor (). NewInstance (); method.invoke (currentObject, newObject); currentObject = newObject;} else {currentObject = tempObject }}

When the code loop processing in this era is complete, currentObject represents an object that can make setter method calls, and in theory, the object must not be null, and then we can use the object to make setter method calls in the way we did before.

Example: implement the cascading property settings of an object

/ / set Field field = currentObject.getClass (). GetDeclaredField (temp [temp. Length-1]); / / get member Method setMethod = currentObject.getClass (). GetDeclaredMethod ("set" + StringUtils.initcap (temp [temp. length-1]), field.getType (); Object convertValue = BeanUtils.convertAttributeValue (field.getType (). GetName (), attval [1]); setMethod.invoke (currentObject, convertValue) / / call the setter method to set the content. Thank you for reading. The above is the content of "what is cascading object instantiation". After the study of this article, I believe you have a deeper understanding of what cascading object instantiation is, and the specific usage needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report