package com.qf.reflection1; import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method; class Student {
private String name;
private int age; public String getName() {
return name;
} private void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public Student(String name, int age) {
super();
this.name = name;
this.age = age;
} public Student() {
super();
} } public class Test { public static void main(String[] args) { try {
// 使用反射第一步 得到某个类的Class对象
Class<Student> clazz1 = Student.class;
Class<?> clazz2 = Class.forName("com.qf.reflection1.Student");
Student student = new Student();
Class<?> clazz3 = student.getClass(); System.out.println("访问类所有属性");
// clazz1.getDeclaredField("age");// 根据属性名 得到属性值 私有的也能得到
// clazz1.getField("name");// 只能得到有访问权限的指定属性
// clazz1.getFields();//得到有访问权限的所有属性
Field fields[] = clazz1.getDeclaredFields();
for (Field field : fields) {
System.out.println(field);
} // 通过反射创建Student对象
// 1,得到无参构造方法
Constructor<Student> constructor = clazz1.getConstructor();
// 2,创建对象
Student stu = constructor.newInstance();
// 等价于 Student stu = new Student(); // 调用setName
// 1,得到setName()
Method method = clazz1.getDeclaredMethod("setName", new Class[] { String.class });
// 私有方法需要设置访问权限
method.setAccessible(true);
// 2,通过之前的student对象调用setName表示的方法
method.invoke(stu, new Object[] { "尼古拉斯赵四" }); // 1,得到getName()
Method getName = clazz1.getDeclaredMethod("getName", new Class[] {});
// 2,通过之前的student对象调用getName表示的方法
Object object = getName.invoke(stu, new Object[] {});
System.out.println(object); } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } }