How To Invoke setter Method using Reflection API. but the Problem is that we don't specify the Field Name , Method Name like
Method method = User.class.getDeclaredMethod("setName", String.class);
method.setAccessible(true);
method.invoke(user, "Some name");
And Also This
TestClass igsm = new TestClass();
User user = new User();
Method methodName= igsm.getMethod("name",user.getClass(),"setter");
methodName.setAccessible(true);
igsm.invokeSetter(user,"Sanket",methodName);
In That cases we just specify the Method Name , Field Name then we set the value bases of Method Name , Field Name.
I want does not specify anything. And check on the base of value which setter method is called.I can not hard code anything in the program. and extract all the information on runtime and set the value in the appropriate method.
That way we can easily invoke the private setter Method by Reflection. I have only specify the value then it will identify which setter method to invoke.
//MainMethod
public static class InvokeMain
{
public static void main(String... args) throws Throwable
{
Object obj1 = getBean("www.Fouth.User");
System.out.println(obj1.toString());
}
}
//Customize Method
public static void extractMethod(Method[] method,Object valueObj,Object classObj) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException
{
for(Method m:method)
{
Type[] pType = m.getGenericParameterTypes();
for(int i=0;i<pType.length; i++)
{
System.out.println("The pType[]"+pType[i]);
if(valueObj.getClass().equals(pType[i]))
{
m.setAccessible(true);
m.invoke(classObj,valueObj.getClass().toString().valueOf(valueObj));
}
}
}
}
//ReflectionMethod
public static Object getBean(String beanClassName) throws Exception
{
Class klass = Class.forName(beanClassName);
Object obj = klass.newInstance();
Method[] b = klass.getDeclaredMethods();
RefLevel3.extractMethod(b,"sanket",obj);
RefLevel3.extractMethod(b,23,obj);
return obj;
}