是一种底层技术,通常用于底层框架的编写
类名.class
Class<类名> 对象名=类名.class
对象名.getClass()
Class 对象名=对象名.getClass();
Class.forName
Class 对象名=Class.forName("类的全限定名");
public static void main(String[] args) throws Exception{
Class<Student> c1 = Student.class;
Student stu = new Student();
Class c2 = stu.getClass();
Class c3 = Class.forName("com.by.entity.Student");
}
public static void main(String[] args) throws Exception{
Class<Student> c1 = Student.class;
Student stu1 = c1.newInstance();
Class c3 = Class.forName("com.by.entity.Student");
//获取的对像默认为Object类型,需要进行类型强转
Student stu2 = (Student) c3.newInstance();
stu1.setName("张三");
stu2.setName("李四");
System.out.println(stu1);
System.out.println(stu2);
//获取全属性的有参构造器对象
//Constructor<Student> con = c1.getDeclaredConstructor(String.class, int.class, double.class);
Constructor<Student> con = c3.getDeclaredConstructor(String.class, int.class, double.class);
//利用有参构造器对象构建类的实例
Student stu3 = con.newInstance("张三", 20, 99.5);
System.out.println(stu3);
}