用反射获取和设置嵌套属性



get or set values of the Nested Property using C# Reflection

        private void button2_Click(object sender, EventArgs e)
        {
            Person p1 = new Person();
            Customer c1 = new Customer { Title = "tt", Surname = "ss" };
            p1.Bill = c1;
            object pp = GetPropValue("Bill.Title", p1);
            this.Text = pp.ToString();
            SetProperty("Bill.Title", p1,"pi1");
            object pp1 = GetPropValue("Bill.Title", p1);
            this.Text = pp1.ToString();
            PropertyInfo pi1 = GetProp(p1.GetType(), "Bill.Title");           
        }
        public class Person
        {
            public Customer Bill { get; set; }

        }
        public class Customer
        {
            public string Title { get; set; }
            public string Surname { get; set; }
        }
        public Object GetPropValue(String name, Object obj)
        {
            foreach (String part in name.Split('.'))
            {
                if (obj == null) { return null; }

                Type type = obj.GetType();
                PropertyInfo info = type.GetProperty(part);
                if (info == null) { return null; }

                obj = info.GetValue(obj, null);
            }
            return obj;
        }
        public PropertyInfo GetProp(Type baseType, string propertyName)
        {
            string[] parts = propertyName.Split('.');

            return (parts.Length > 1)
                ? GetProp(baseType.GetProperty(parts[0]).PropertyType, parts.Skip(1).Aggregate((a, i) => a + "." + i))
                : baseType.GetProperty(propertyName);
        }
        private static System.Reflection.PropertyInfo GetProperty(object t, string PropertName)
        {
            if (t.GetType().GetProperties().FirstOrDefault(p => p.Name == PropertName.Split('.')[0]) == null)
                throw new ArgumentNullException(string.Format("Property {0}, is not exists in object {1}", PropertName, t.ToString()));
            if (PropertName.Split('.').Length == 1)
                return t.GetType().GetProperty(PropertName);
            else
                return GetProperty(t.GetType().GetProperty(PropertName.Split('.')[0]).GetValue(t, null), PropertName.Split('.')[1]);
        }
        public void SetProperty(string compoundProperty, object target, object value)
        {
            string[] bits = compoundProperty.Split('.');
            for (int i = 0; i < bits.Length - 1; i++)
            {
                PropertyInfo propertyToGet = target.GetType().GetProperty(bits[i]);
                target = propertyToGet.GetValue(target, null);
            }
            PropertyInfo propertyToSet = target.GetType().GetProperty(bits.Last());
            propertyToSet.SetValue(target, value, null);
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果你想使用Java将Excel数据导入到嵌套对象中,可以使用Apache POI和Java反射。 以下是一个示例代码,演示了如何动态填充嵌套对象属性值: 假设我们有以下两个类: ```java public class Address { private String street; private String city; private String state; private String zipCode; // getters and setters } public class Person { private String name; private int age; private Address address; // getters and setters } ``` 假设我们已经将Excel表格中的数据读入到了一个List<List<String>>对象中,其中每个List<String>对象表示一行Excel数据。下面的代码展示了如何使用反射和Apache POI将数据填充到Person对象中: ```java import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.Row; import java.lang.reflect.Field; import java.util.List; public class ExcelReader { public static void main(String[] args) { // 假设我们已经将Excel表格中的数据读入到了一个List<List<String>>对象中 List<List<String>> excelData = getExcelData(); // 创建一个名为"Sheet1"的工作表 Sheet sheet = workbook.getSheet("Sheet1"); // 获取工作表中的数据行 for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) { Row row = sheet.getRow(i); // 创建Person对象 Person person = new Person(); // 使用反射获取Person对象中的所有属性 Field[] fields = Person.class.getDeclaredFields(); // 遍历所有属性 for (int j = 0; j < fields.length; j++) { Field field = fields[j]; // 获取属性名 String fieldName = field.getName(); // 获取属性值 Cell cell = row.getCell(j); Object cellValue = null; if (cell != null) { CellType cellType = cell.getCellType(); if (cellType == CellType.STRING) { cellValue = cell.getStringCellValue(); } else if (cellType == CellType.NUMERIC) { cellValue = cell.getNumericCellValue(); } } // 如果属性值为null,则跳过 if (cellValue == null) { continue; } // 如果属性名为address,则填充Address对象属性值 if (fieldName.equals("address")) { // 创建Address对象 Address address = new Address(); // 获取Address对象中的所有属性 Field[] addressFields = Address.class.getDeclaredFields(); // 遍历所有属性 for (int k = 0; k < addressFields.length; k++) { Field addressField = addressFields[k]; // 获取属性名 String addressFieldName = addressField.getName(); // 获取属性值 Cell addressCell = row.getCell(j + k + 1); Object addressCellValue = null; if (addressCell != null) { CellType addressCellType = addressCell.getCellType(); if (addressCellType == CellType.STRING) { addressCellValue = addressCell.getStringCellValue(); } else if (addressCellType == CellType.NUMERIC) { addressCellValue = addressCell.getNumericCellValue(); } } // 如果属性值为null,则跳过 if (addressCellValue == null) { continue; } // 使用反射设置Address对象属性值 try { Field addressField = Address.class.getDeclaredField(addressFieldName); addressField.setAccessible(true); addressField.set(address, addressCellValue); } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } } // 设置Person对象的address属性值 person.setAddress(address); } else { // 使用反射设置Person对象属性值 try { field.setAccessible(true); field.set(person, cellValue); } catch (IllegalAccessException e) { e.printStackTrace(); } } } // 打印Person对象属性值 System.out.println(person); } } } ``` 这个示例代码中,我们首先使用反射获取了Person类中的所有属性,然后遍历了Excel表格中的数据行,并使用反射和Apache POI将数据填充到Person对象中。当属性名为address时,我们创建了一个新

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值