javaSE注解和反射之获取类的运行时结构
程序员文章站
2022-06-16 17:29:37
...
package 反射;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class 获取类的运行时结构 {
public static void main(String[] args) throws Exception {
Class c1= Class.forName("反射.pojo.User");
//获取类的名字
String name1 = c1.getName();
String SimpleName = c1.getSimpleName();
System.out.println(name1);
System.out.println(SimpleName);
//获取类的属性
System.out.println("===================================================");
Field[] fields1=c1.getFields();//只能找到public属性
for (Field field : fields1) {
System.out.println(field);
}
System.out.println("=====================================================");
Field[] fields2=c1.getDeclaredFields();
for (Field field : fields2) {
System.out.println(field);
}
//获得指定属性的值
Field name = c1.getDeclaredField("name");
System.out.println(name);
//获取类的方法
System.out.println("===============================");
//获取本类及其父类的全部public
Method[] methods1 = c1.getMethods();
for (Method method : methods1) {
System.out.println(method);
}
System.out.println("================================");
//获取本类的所有方法
Method[] methods2 = c1.getDeclaredMethods();
for (Method method : methods2) {
System.out.println(method);
}
//获取指定方法
Method getName = c1.getMethod("getName", null);
Method setName = c1.getMethod("setName", String.class);
System.out.println(getName);
System.out.println(setName);
//获得指定的构造器
Constructor[] constructors = c1.getConstructors();
for (Constructor constructor : constructors) {
System.out.println(constructor);
}
Constructor[] declaredConstructors = c1.getDeclaredConstructors();
for (Constructor declaredConstructor : declaredConstructors) {
System.out.println("#"+declaredConstructor);
}
//获得指定的构造器
Constructor constructor = c1.getDeclaredConstructor(String.class, String.class, int.class);
System.out.println(constructor);
}
}
上一篇: 我做的第一个表单