文章摘要:
小白零基础快速入门Java —— 第十三课:Java高级之反射。本文介绍了以下内容:1、反射的概念。2、通过反射获取类、构造器、成员变量、成员方法。3、反射的作用和应用场景。
1、认识反射
2、获取类
public class CollectionTest {
public static void main(String[] args) throws ClassNotFoundException {
Class c1 = student.class;
System.out.println(c1.getName()); // 全类名 运行结果:com.self.collection.student
System.out.println(c1.getSimpleName()); // 简名 运行结果:student
Class c2 = Class.forName("com.self.collection.student");
student s = new student();
Class c3 = s.getClass();
System.out.println(c3);
}
}
3、获取类的构造器
public class CollectionTest {
public static void main(String[] args) throws NoSuchMethodException {
Class c = student.class;
Constructor[] constructors = c.getConstructors(); // 缺点:只能获取public修饰的构造器
for (Constructor constructor: constructors){
System.out.println(constructor.getName() + "---->" + constructor.getParameterCount());
// 运行结果
// com.self.collection.student---->0
// com.self.collection.student---->2
}
// Constructor con = c.getConstructor(); // 获取类中的无参构造器 , 只能获取public修饰的
Constructor con = c.getDeclaredConstructor(); // 获取类中的无参构造器, private修饰的也能获取
Constructor con1 = c.getDeclaredConstructor(String.class, int.class); // 获取类中的有参构造器, private修饰的也能获取
}
}
student stu = (student) constructor.newInstance(); //使用无参数构造器初始化对象
4、获取类的成员变量
5、获取类的成员方法
6、作用、应用场景