Java 如何使用反射API调用Setter方法,但不提及FieldName&;之类的内容;方法名
如何使用反射API调用setter方法。但是问题是我们没有指定字段名,方法名,比如Java 如何使用反射API调用Setter方法,但不提及FieldName&;之类的内容;方法名,java,spring,dependency-injection,inversion-of-control,Java,Spring,Dependency Injection,Inversion Of Control,如何使用反射API调用setter方法。但是问题是我们没有指定字段名,方法名,比如 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 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方法。我不能在程序中硬编码任何东西。并提取运行时的所有信息,并在适当的方法中设置值。这样我们就可以通过反射轻松调用private 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;
}
//main方法
公共静态类InvokeMain
{
publicstaticvoidmain(字符串…参数)抛出Throwable
{
对象obj1=getBean(“www.Fouth.User”);
System.out.println(obj1.toString());
}
}
//自定义方法
公共静态void extractMethod(方法[]方法,对象值obj,对象类obj)抛出IllegalAccessException、IllegalArgumentException、InvocationTargetException
{
用于(方法m:方法)
{
Type[]pType=m.getGenericParameterTypes();
对于(int i=0;i“不指定任何内容”是什么意思?您需要告诉reflection您要调用的方法。但只指定方法名称,我们不指定参数类型和文件名。只调用方法名称的setter base是可能的。我们不提取reflection中的任何内容“base”是什么意思至少,不接受任何参数?Spring调用setter,该setter知道如何设置字段和要设置的字段。