如何在Java中通过反射调用setter方法 [英] how to invoke setter method by reflection in java

查看:358
本文介绍了如何在Java中通过反射调用setter方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过反射在Java中调用Bean私有setter方法

how to invoke Bean private setter method by reflection in java

我不明白如何在我的用户Bean"中调用私有setter方法. 我都准备好使用PropertyDescriptor和许多方法,但是我无法访问private 反射的二传手方法.

I can't Understand how to invoke private setter Method in My User Bean. I all ready used PropertyDescriptor and many way but i am not access private setter method by the Reflection.

public class GetterAndSetter
 {
     public static void main(String[] args)
     {
         GetterAndSetter gs = new GetterAndSetter();
         User user = new User();

          try {
            gs.callSetter(user,"name","Sanket");
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IntrospectionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

     }

     private void callSetter(Object obj,String fieldName, Object value) throws IntrospectionException, InvocationTargetException, IllegalAccessException , IllegalArgumentException
     {
         PropertyDescriptor pd;

         pd = new PropertyDescriptor(fieldName,obj.getClass());
         pd.getWriteMethod().invoke(obj,value);
     }

 }

此代码我将只访问字段并设置字段中的值,但我不能 直接将Setter字段访问到Reflection

This Code I would only access the filed and set the value in filed,But I can't access the setter Field directly to the Reflection

推荐答案

如何在User类中调用私有方法:

This how you can call a private method in the User class:

try {
    User user = new User();
    Method method = User.class.getDeclaredMethod("setName", String.class);
    method.setAccessible(true);
    method.invoke(user, "Some name");
    System.out.println("user.getName() = " + user.getName());
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
    e.printStackTrace();
}

注意对method.setAccessible(true);

这篇关于如何在Java中通过反射调用setter方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆