[size=14.0000009536743px]3、 写一个方法,此方法可将obj对象中名为propertyName的属性的值设置为value.
[size=14.0000009536743px]public void setProperty(Object obj, String propertyName, Object value){
[size=14.0000009536743px]}
[size=14.0000009536743px]4、 ArrayList list = new ArrayList(); 在这个泛型为Integer的ArrayList中存放一个String类型的对象。
答案:
第三题:
package 反射题;
import java.lang.reflect.Method;
import java.util.ArrayList;
//refelect越过泛型检查
public class fanxingjiancha {
public static void main(String[] args) throws Exception {
//新建集合
ArrayList arr=new ArrayList();
arr.add(12);
arr.add(34);
//反射加入 字符串
Class clazz=Class.forName("java.util.ArrayList");
Method add=clazz.getMethod("add",Object.class);
add.invoke(arr, "adfsf");
System.out.println(arr);
}
}
第四题:
package 反射题;
import java.lang.reflect.Field;
public class xiugaiduixiangzhi {
//修改对象属性值
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
student s=new student();
s.setName("damaha");
System.out.println(s);
xiugaiduixiangzhi xiugai=new xiugaiduixiangzhi();
xiugai.setProperty(s, "name", "hahahah");
System.out.println(s);
}
public void setProperty(Object obj, String propertyName, Object value) throws Exception{
Class clazz=obj.getClass();
Field field=clazz.getDeclaredField(propertyName);
field.setAccessible(true);
field.set(obj, value);
}
}
class student {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "student [name=" + name + "]";
}
public student() {
super();
// TODO Auto-generated constructor stub
}
public student(String name) {
super();
this.name = name;
}
}
|
|