簡體   English   中英

如何在不使用setter的情況下將值設置為類變量

[英]How to set values to a class variables without using setters

我想在不使用setter的情況下向Object變量插入值。 怎么可能。

這是一個例子

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

現在我有一個函數,它包含variable namevalue to be setvalue to be setObject of the Class XObject of the Class X

我正在嘗試使用泛型方法將值設置為Object(objectOfClass),並在相應的變量( variableName )中傳遞值i( valueToBeSet )。

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

如果你確定你真的需要這個,請三思,但無論如何:

import java.lang.reflect.Field;
...
X x = new X();
Field variableName = x.getClass().getDeclaredField("variableName");

// this is for private scope
variableName.setAccessible(true);

variableName.set(x, "some value");

此代碼未經過測試。 你可以試試這個。

要導入的類

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

在對象中設置值有兩種方法

1- 構造函數注入 - 通過構造函數參數將依賴項“推送”到具體類中。

2- Setter Injection - 通過公共屬性將依賴性“推送”到具體類中。 “Setter”命名法取自Java,其中屬性是getSomething()和setSomething(value)。

由於您不想使用setter,您可以創建一個參數化構造函數來執行此操作。參數化構造函數需要在創建對象時傳遞參數。除此之外,我認為沒有任何其他方法可以在不調用的情況下執行此操作。 setter方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM