一、获取字节码信息
- 对象名.getClass():
Class c3 = Class.forName("com.test01.Person");
- 类名.class:
Class c2 = Person.class;
- Class.forName(“类的全限定名”):
Class c3 = Class.forName("com.test01.Person");
- 类加载器.load(“类的全限定名”):
Class c4 = MyTest.class.getClassLoader().loadClass("com.test01.Person");
二、Class类的实例类型
-
demo
@Test public void testForClassInstanceType() { /*可以作为Class类的实例的种类 (1) 类:外部类、内部类 (2) 接口 (3) 注解 (4) 数组 (5) 基本数据类型 (6) void */ Class personClass = Person.class; Class comparableClass = Comparable.class; Class overrideClass = Override.class; int[] arr1 = {1, 2, 3}; Class c1 = arr1.getClass(); int[] arr2 = {1, 2, 3}; Class c2 = arr2.getClass(); System.out.println(c1 == c2); Class<Integer> i1 = int.class; Class<Integer> i2 = Integer.class; System.out.println(i1 == i2); Class<Void> voidClass = void.class; }
三、获取类的接口
-
代码
@Test public void testForGetClassInterface() { Class<Student> studentClass = Student.class; //获取实现的接口 Class<?>[] interfaces = studentClass.getInterfaces(); for (Class<?> anInterface : interfaces) { System.out.println(anInterface); } //获取父类 Class<? super Student> superclass = studentClass.getSuperclass(); System.out.println(superclass); }
四、获取类的构造器
-
代码
@Test public void testForGetConstructor() throws Exception { Class<Student> studentClass = Student.class; //获取全部修饰符的构造器 Constructor<?>[] declaredConstructors = studentClass.getDeclaredConstructors(); for (Constructor<?> declaredConstructor : declaredConstructors) { System.out.println(declaredConstructor); } System.out.println("=============================="); //获取指定的构造器 Constructor<Student> constructor = studentClass.getConstructor(); System.out.println(constructor); Constructor<Student> constructor1 = studentClass.getConstructor(double.class, double.class); System.out.println(constructor1); //根据构造器创建对象 Student student = constructor.newInstance(); System.out.println(student); Student student1 = constructor1.newInstance(22, 56); System.out.println(student1); }
五、获取类的属性
-
代码
@Test public void testForGetFild() throws Exception { Class<Student> studentClass = Student.class; //获取属性 Field sno = studentClass.getDeclaredField("name"); //根据注解类型获取属性注解 MyAnnotation annotation = sno.getAnnotation(MyAnnotation.class); Student student = studentClass.newInstance(); System.out.println(annotation.value()); //给属性赋值 sno.set(student, annotation.value()); System.out.println(student); }
六、获取类的方法
-
代码
@Test public void testForGetMethod() throws Exception { Class<Student> studentClass = Student.class; //获取方法 Method showInfo = studentClass.getMethod("showInfo"); Student student = studentClass.newInstance(); //调用方法 showInfo.invoke(student); }