通过反射机制访问对象属性
public class Teacher {
public int no;
String name;
boolean sex;
public Teacher() {
}
public Teacher(int no) {
this.no = no;
}
public Teacher(int no, String name, boolean sex) {
this.no = no;
this.name = name;
this.sex = sex;
}
}
import java.lang.reflect.Field;
public class ReflexTest01 {
public static void main(String[] args) throws Exception {
Class c=Class.forName("Teacher");
Object obj= c.newInstance();
Field noFiled=c.getDeclaredField("no");
noFiled.set(obj,222);//给obj对象的no属性赋值222
System.out.println(noFiled.get(obj));
}
}
通过反射机制调用对象方法
可变长度参数 (int…args)一定是三个点
1.可变长度参数要求的参数个数是0-n个。
2.可变长度参数在参数列表中必须在最后一个位置上,而且可变长度参数只能有一个。
3.args又length属性,可以将可变长度参数当作一个数组来看。
public class Teacher {
public int no;
String name;
boolean sex;
public Teacher() {
}
public Teacher(int no) {
this.no = no;
}
public Teacher(int no, String name, boolean sex) {
this.no = no;
this.name = name;
this.sex = sex;
}
public void doSome(int i,String name){
System.out.println(name+i);
}
}
import java.lang.reflect.Method;
public class ReflexTest02 {
public static void main(String[] args) throws Exception {
Class c=Class.forName("Teacher");
Object obj=c.newInstance();
Method doSomeMethod=c.getDeclaredMethod("doSome", int.class, String.class);
doSomeMethod.invoke(obj,5,"zhangsan");
}
}