进阶day12-Class对象的三种获取方式
This commit is contained in:
37
javaSE-day12/src/com/inmind/refelct02/Demo02.java
Normal file
37
javaSE-day12/src/com/inmind/refelct02/Demo02.java
Normal file
@@ -0,0 +1,37 @@
|
||||
package com.inmind.refelct02;
|
||||
/*
|
||||
反射:在程序运行时,操作类(构造方法,成员方法,成员变量)
|
||||
反射前提是Class对象!!
|
||||
|
||||
--------------------------------------------------
|
||||
Class对象的三种获取方式
|
||||
1.Class.forName("全类名") 常用于框架的初始化操作(jdbc注册驱动)
|
||||
全类名:包名+类名
|
||||
2.类名.class 常用于反射API中作为参数
|
||||
|
||||
3.对象名.getClass() 常用于类型判断
|
||||
*/
|
||||
public class Demo02 {
|
||||
public static void main(String[] args) throws ClassNotFoundException {
|
||||
//Class对象的获取方式一:
|
||||
Class<?> clazz1 = Class.forName("com.inmind.refelct02.Student");
|
||||
System.out.println(clazz1);
|
||||
|
||||
//Class对象的获取方式二:
|
||||
Class<Student> clazz2 = Student.class;
|
||||
System.out.println(clazz2);
|
||||
|
||||
//Class对象的获取方式三:
|
||||
Student s = new Student();
|
||||
Class<? extends Student> clazz3 = s.getClass();
|
||||
System.out.println(clazz3);//Class类中toString重写过了
|
||||
|
||||
//注意:一个类的字节码文件只有一个,与之对应的描述对象也只有一个,那么clazz1、clazz2、clazz3其实是同一个对象
|
||||
System.out.println(clazz1 == clazz2);//true
|
||||
System.out.println(clazz3 == clazz2);//true
|
||||
|
||||
//Class对象的常用方法
|
||||
System.out.println(clazz1.getName());//全类名:com.inmind.refelct02.Student
|
||||
System.out.println(clazz1.getSimpleName());//类名:Student
|
||||
}
|
||||
}
|
||||
5
javaSE-day12/src/com/inmind/refelct02/Student.java
Normal file
5
javaSE-day12/src/com/inmind/refelct02/Student.java
Normal file
@@ -0,0 +1,5 @@
|
||||
package com.inmind.refelct02;
|
||||
|
||||
public class Student {
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user