[英]How To Invoke Setter Method using Reflection API But does not mention anything like FieldName & MethodName
如何使用反射 API 调用 setter 方法。 但问题是我们没有指定 Field Name , Method Name 之类的
Method method = User.class.getDeclaredMethod("setName", String.class);
method.setAccessible(true);
method.invoke(user, "Some name");
还有这个
TestClass igsm = new TestClass();
User user = new User();
Method methodName= igsm.getMethod("name",user.getClass(),"setter");
methodName.setAccessible(true);
igsm.invokeSetter(user,"Sanket",methodName);
在这种情况下,我们只指定方法名称、字段名称,然后我们设置方法名称、字段名称的值基础。
我想不指定任何东西。 并检查调用哪个 setter 方法的值的基础。我不能在程序中硬编码任何东西。 并提取有关运行时的所有信息并在适当的方法中设置值。
这样我们就可以很容易地通过反射调用私有的 setter 方法。 我只指定了该值,然后它将确定要调用哪个 setter 方法。
//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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.