程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了如何在不使用设置器的情况下为类变量设置值大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

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

开发过程中遇到如何在不使用设置器的情况下为类变量设置值的问题如何解决?下面主要结合日常开发的经验,给出你关于如何在不使用设置器的情况下为类变量设置值的解决方法建议,希望对你解决如何在不使用设置器的情况下为类变量设置值有所启发或帮助;

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

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;
    }

解决方法

我想在Object不使用设置器的情况下将值插入变量。如果有可能怎么办。

这是一个例子

Class X{
String variablename;
// getters and setters
}

现在我有一个包含variable namevalue to be set和的函数Object of the Class X

我试图使用一种通用方法将值设置为Object(objectOfClass),而值我已经valueToBeSet相应的variable(variablename)中通过了()。

Object functionName(String variablename,Object valueToBeSet,Object objectOfClass){

    //I want to do the exact same thing as it does when setTing the value using the below statement
    //objectOfClass.setX(valueToBeSet);

return objectOfClass;
}

大佬总结

以上是大佬教程为你收集整理的如何在不使用设置器的情况下为类变量设置值全部内容,希望文章能够帮你解决如何在不使用设置器的情况下为类变量设置值所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。