如何通过反射在Java中调用Bean私有setter方法
我不明白如何在“我的用户Bean”中调用私有setter方法。 我都准备好使用PropertyDescriptor和许多方法,但我无法访问私有 反射的二传手方法。
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);
}
}
此代码我只能访问字段并设置字段中的值,但是我不能 直接将设置者字段访问到反射
答案 0 :(得分:1)
如何在User
类中调用私有方法:
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);
的呼叫