您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

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

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;
    }
其他 2022/1/1 18:30:25 有409人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶