![](/img/trans.png)
[英]Java - Reflection. Set Value in the setter method multiple argument class object which are dynamically created
[英]Java - Reflection. Set value for the class object which are dynamically created
嗨,我有一個我在運行時動態創建對象的類[許多]。 現在我想為which are private fields
設置值。 我該如何設置它們。
我已經看到許多示例來解釋這一點,但是我們需要知道字段名稱,而且只能設置值。
就我而言,我為一組原始類型和非原始類型提供了一組默認值,並在運行時查找字段類型並為其設置了默認值。
例如:
LoginBean loginBean = new LoginBean();
Method setUserName = loginBean.getClass().getMethod("setUserName", new Class[]{String.class});
setUserName.invoke(loginBean, "myLogin");
我的情況不同,我什至不知道field name
但必須根據字段類型設置默認值。
如何使用反射甚至在春季更好地做到這一點。
您可以說yourBean.class.getFields();
這將給出Field的數組。
使用Field
可以找到其name
和type
,並完成所需的工作(如果其類型為==一些原始類型,則可以設置一些值)
本示例使用反射在類中的幾個字段上設置默認值。 這些字段具有私有訪問權限,可通過反射將其打開和關閉。 Field.set()
用於在特定實例上設置字段的值,而不是使用setter方法。
import java.lang.reflect.Field;
import java.util.Date;
public class StackExample {
private Integer field1 = 3;
private String field2 = "Something";
private Date field3;
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
StackExample se = new StackExample();
Field[] fields = se.getClass().getDeclaredFields();
for(Field f:fields){
if(!f.isAccessible()){
f.setAccessible(true);
Class<?> type = f.getType();
if(type.equals(Integer.class)){
f.set(se, 100); //Set Default value
}else if(type.equals(String.class)){
f.set(se, "Default");
}else if (type.equals(Date.class)){
f.set(se, new Date());
}
f.setAccessible(false);
}
System.out.println(f.get(se)); //print fields with reflection
}
}
}
1)通過使用Spring構造器/ Setter注入。 您不需要知道屬性名稱,只需鍵入即可。 如下所示:
<bean id="myBean" class="myBean">
<constructor-arg type="int"><value>1</value></constructor-arg>
</bean>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.