public class TestReflect01 {
public static void main(String[] args) throws Exception{
//得到Person的Class对象
Class clazz = Class.forName("test.reflect1.Person");
/*
* 测试Person类构造方法的反射
* 这段代码将Person的每个构造方法都反射成一个Constructor类,这个Contructor类里面有构造方法的名字,参数类型等等信息
* 通过Contructor类的newInstance()方法就相当于调用Person的构造方法
* Contructor类带有泛型,可以明确newIntance()方法返回的类型
*/
Constructor<Person> construct1 = clazz.getConstructor();
Constructor construct2 = clazz.getConstructor(String.class,int.class,String.class);
Constructor[] constructs = clazz.getConstructors();
Person p =construct1.newInstance();
Object obj = construct2.newInstance("aa",1,"aa");
for(Constructor c:constructs){
System.out.println(c.getName());
}
/*
* 测试Person类Field的反射
* getField(String)和getDeclaredField(String)方法的区别:(构造方法,方法等雷同)
* getField(String)只能得到public修饰的属性
* getDeclaredField(String)能得到所有的属性,即使是被private修饰的属性
*/
Field field1 = clazz.getDeclaredField("sex");
System.out.println(field1.isAccessible());
System.out.println(field1.getName());
Field[] fields = clazz.getDeclaredFields();
for(Field field:fields){
System.out.println(field.getName());
}
/*
* 测试方法的反射
*/
Method method = clazz.getMethod("setAge", int.class);
method.invoke(new Person(), 1);
String[] a = new String[3];
System.out.println(a.getClass().getName());
}
}
class Person{
private String name;
protected int age;
String sex;
public Person(){
System.out.println("Person's constructot without paratemers");
}
public Person(String name,int age,String sex){
/*this.name = name;
this.age =age;
this.sex = sex;*/
System.out.println("Person's constructot with paratemers");
}
public int getAge() {
return age;
}
public void setAge(int age) {
System.out.println("Person's setAge method"+age);
this.age = age;
}
}
|
|