根据入参通过反射获取入参字段名及对应的值

public BaseApiReturnJson CommonMethod(Dto pDto){
     Field[] fields = pDto.getClass().getDeclareFields();
     try{
        for( int i = 0 ; i < fields.length() ; i++){ //根据入参循环取出对应类的属性名及值
            String fieldName = fields[i].getName();//获取的字段名        
            Field field  = pDto.getClass().getField(fieldName);
            field.setAccessible(true);//设置对象的访问权限,保证private属性的访问权限
            String value = (String)field.get(pDto);//获取字段名对应的值
        }
        }catch(Exception e){
            logger.info("反射获取属性名及对应的值出错");
        }
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用反射获取实体类中所有字段的属性,然后通过自定义属性或者约定俗成的规则,获取每个字段对应的数据库字段名。 以下是一个示例代码: ```csharp using System; using System.Collections.Generic; using System.Linq; using System.Reflection; public static class DatabaseUtility { public static Dictionary<string, string> GetDatabaseFields(string entityClassName, string prefix = "") { var entityAssembly = Assembly.GetExecutingAssembly(); // 获取实体类所在的程序集 var entityClass = entityAssembly.GetTypes().FirstOrDefault(t => t.Name == entityClassName); // 获取实体类的 Type if (entityClass == null) { throw new ArgumentException($"Entity class {entityClassName} not found in assembly."); } var databaseFields = new Dictionary<string, string>(); foreach (var field in entityClass.GetFields(BindingFlags.Public | BindingFlags.Instance)) { var fieldName = prefix + field.Name; // 默认情况下,数据库字段名与实体类字段名相同,可以通过数 prefix 添加前缀 var databaseFieldAttribute = field.GetCustomAttribute<DatabaseFieldAttribute>(); if (databaseFieldAttribute != null) { fieldName = databaseFieldAttribute.FieldName; } databaseFields.Add(field.Name, fieldName); } return databaseFields; } } // 自定义属性,用于标记实体类中的字段对应的数据库字段名 [AttributeUsage(AttributeTargets.Field)] public class DatabaseFieldAttribute : Attribute { public string FieldName { get; } public DatabaseFieldAttribute(string fieldName) { FieldName = fieldName; } } ``` 使用示例: ```csharp public class User { [DatabaseField("id")] public int Id; [DatabaseField("username")] public string Username; [DatabaseField("password")] public string Password; } var databaseFields = DatabaseUtility.GetDatabaseFields("User", "u_"); foreach (var pair in databaseFields) { Console.WriteLine($"Entity field {pair.Key} maps to database field {pair.Value}."); } // 输出: // Entity field Id maps to database field u_id. // Entity field Username maps to database field u_username. // Entity field Password maps to database field u_password. ``` 注意:上述代码中使用了自定义属性 `DatabaseFieldAttribute`,可以根据实际情况进行修改。如果没有自定义属性,可以约定俗成地将实体类字段名转为小写,然后添加下划线前缀作为数据库字段名
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值