如何在不使用设置器的情况下为类变量设置值

如何在不使用设置器的情况下为类变量设置值,第1张

如何在不使用设置器的情况下为类变量设置值

此代码未经测试。你可以试试看

要导入的类

import java.beans.BeanInfo;import java.beans.IntrospectionException;import java.beans.Introspector;import java.beans.PropertyDescriptor;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;

方法

public Object functionName(String variableName, Object valueToBeSet, Object objectOfClass) throws IntrospectionException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{        //I want to do the exact same thing as it does when setting the value using the below statement        //objectOfClass.setX(valueToBeSet);        Class clazz = objectOfClass.getClass();        BeanInfo beanInfo = Introspector.getBeanInfo(clazz, Object.class); // get bean info        PropertyDescriptor[] props = beanInfo.getPropertyDescriptors(); // gets all info about all properties of the class.        for (PropertyDescriptor descriptor : props) { String property = descriptor.getDisplayName(); if(property.equals(variableName)) {     String setter = descriptor.getWriteMethod().getName();     Class parameterType = descriptor.getPropertyType();     Method setterMethod = clazz.getDeclaredMethod(setter, parameterType); //Using Method Reflection     setterMethod.invoke(objectOfClass, valueToBeSet); }        }    return objectOfClass;    }


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5502038.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-12
下一篇2022-12-12

发表评论

登录后才能评论

评论列表(0条)

    保存