反射注解之通过Class对象获得类的内部结构
获得类内部结构的代码如下
package com.loubin; import java.lang.annotation.*; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; public class Main { public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException { Class c = User.class; String name = c.getName(); System.out.println(name); System.out.println("获取所有属性-------------------------------"); Field[] fields = c.getDeclaredFields(); for (Field field : fields) { System.out.println(field.getName()); } System.out.println("获取指定属性-----------------------------------"); Field field = c.getDeclaredField("name"); System.out.println(field.getName()); System.out.println("获取所有方法----------------------------------"); Method[] methods = c.getDeclaredMethods(); for (Method method : methods) { System.out.println(method.getName()); } System.out.println("获取指定方法----------------------------------"); Method method = c.getDeclaredMethod("getName"); System.out.println(method.getName()); System.out.println("获取无参构造器------------------------------------"); Constructor constructor = c.getDeclaredConstructor(); System.out.println(constructor.getName()); System.out.println("获取有参构造器-----------------------------------"); Constructor constructor1 = c.getDeclaredConstructor(String.class, int.class); } } class User{ String name; int age; public User() { } public User(String name, int age) { this.name = name; this.age = age; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
测试结果如下

还有getField和getMethod方法我没写,这两个方法只能获得public属性和public方法

浙公网安备 33010602011771号