新建Student类
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public void show(){
System.out.println("姓名"+name);
System.out.println("姓名"+age);
}
public void say(String msg){
System.out.println(name + "说" + msg);
}
}
获得反射并解析
public class StudentReflectDemo {
public static void main(String[] args) {
//获得反射
Class cls = Student.class;
//解析这个类
/**
* cls.getField()获得能访问到的属性
* cle.getDeclaredFields()获得所有属性
*/
Field[] fs = cls.getDeclaredFields();
for (Field f : fs){
System.out.println(f.getName());
}
}
}
- cls.getField()获得能访问到的属性
- cle.getDeclaredFields()获得所有属性
/**
* cls.getConstructor()获得所有可访问的构造
* cls.getDeclaredConstructors()获得所有声明的构造
* c.getName()获得构造名(和类名一致,而且是全类名)
* c.getParameterTypes()获得参数的Class类型数组
*/
Constructor[] cs = cls.getConstructors();
for (Constructor c : cs){
System.out.println(c.getName());
Class[] clss = c.getParameterTypes();
for (Class cc:clss){
System.out.println(cc.getName());
}
System.out.println("------------------");
}
- cls.getConstructor()获得所有可访问的构造
- cls.getDeclaredConstructors()获得所有声明的构造
- c.getName()获得构造名(和类名一致,而且是全类名)
- c.getParameterTypes()获得参数的Class类型数组
/**
* cls.getMethods(); 获得包含父类的方法在内的能访问到的方法
* cls.getDeclaredMethods,获得当前类声明的所有方法,但不包含父类方法
*/
Method[] ms = cls.getDeclaredMethods();
for (Method m : ms){
System.out.println(m.getName());
}
- cls.getMethods(); 获得包含父类的方法在内的能访问到的方法
- cls.getDeclaredMethods,获得当前类声明的所有方法,但不包含父类方法
- m.getName()获得方法名
- m.getReturnType()获得方法的返回值类型
- m.getParameterTypes()获得方法所有的参数Class类型的数组
/*
* 获得反射对象,是可以实例化这个类型对象的
* cls.newInstance()获得反射类型的对象
* */
Student s = (Student)cls.newInstance();
s.age = 18;
s.show();