反射:
获得包名、类名
clazz.getPackage().getName()//包名
clazz.getSimpleName()//类名
clazz.getName()//完整类名
!!成员变量定义信息
getFields()//获得所有公开的成员变量,包括继承的变量
getDeclaredFields()//获得本类定义的成员变量,包括私有,不包括继承的变量
getField(变量名)
getDeclaredField(变量名)
代码:
Demo01.java
package com.fanjia.day20200824;
import java.lang.reflect.Field;
/**
* Created by FanJia on 2020/8/24 18:50
*/
public class Demo01 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class<?> student = Class.forName("com.fanjia.day20200824.Student");
//Class<Student> studentClass = Student.class;
Class<? extends Student> aClass = new Student().getClass();
System.out.println(student.getName());
System.out.println(student.getPackage().getName());
System.out.println(student.getSimpleName());
Field id = student.getField("id");
System.out.println(id);
Field name = student.getDeclaredField("name");
System.out.println(name);
Field[] fields = student.getFields();
System.out.println("=======================");
for(Field field : fields){
System.out.println(field);
}
System.out.println("===========================");
Field[] declaredFields = student.getDeclaredFields();
for (Field field : declaredFields){
System.out.println(field);
}
}
}
Student.java
package com.fanjia.day20200824;
/**
* Created by FanJia on 2020/8/24 18:52
*/
public class Student {
public int id=1;
private String name;
public Student() {
}
public Student(int id) {
this.id = id;
}
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name=" + name +
'}';
}
}