java反射通过字段名获取set、get方法

/*
/*
反射机制:通过字段名和参数获取setter方法
 */
public static Method convertSetter(Class cla, String field, Class<?>... parameterTypes) {
    String str1 = field.substring(0, 1);
    String str2 = field.substring(1, field.length());
    String method_set = "set" + str1.toUpperCase() + str2;
    Method method1 = null;
    try {
        method1 = cla.getMethod(method_set, parameterTypes);
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }
    return method1;
}
反射机制:通过字段名和参数获取setter方法
 */
public static Method convertSetter(Class cla, String field, Class<?>... parameterTypes) {
    String str1 = field.substring(0, 1);
    String str2 = field.substring(1, field.length());
    String method_set = "set" + str1.toUpperCase() + str2;
    Method method1 = null;
    try {
        method1 = cla.getMethod(method_set, parameterTypes);
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }
    return method1;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Java中,可以使用反射机制来实现依据字段名将一个类A转换为类B的操作。反射机制允许我们在运行时动态地获取类的信息,并且可以通过字段名获取和设置字段的值。 下面是一个示例代码,演示了如何使用反射实现将类A转换为类B的操作: ```java import java.lang.reflect.Field; public class ReflectionExample { public static <T, U> U convertClass(T source, Class<U> targetClass) throws Exception { U target = targetClass.getDeclaredConstructor().newInstance(); Field[] sourceFields = source.getClass().getDeclaredFields(); Field[] targetFields = targetClass.getDeclaredFields(); for (Field sourceField : sourceFields) { for (Field targetField : targetFields) { if (sourceField.getName().equals(targetField.getName())) { sourceField.setAccessible(true); targetField.setAccessible(true); targetField.set(target, sourceField.get(source)); break; } } } return target; } public static void main(String[] args) throws Exception { // 定义类A和类B class A { private String name; private int age; public A(String name, int age) { this.name = name; this.age = age; } } class B { private String name; private int age; public B() {} public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } // 创建类A的实例 A a = new A("John", 25); // 将类A转换为类B B b = convertClass(a, B.class); // 输出转换后的结果 System.out.println("Name: " + b.getName()); System.out.println("Age: " + b.getAge()); } } ``` 上述代码中,`convertClass`方法使用了泛型,可以接受任意类型的源对象和目标类。它通过反射获取源对象和目标类的字段,并根据字段名进行匹配和赋值操作。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值