package com.cheng.reflection;
?
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
?
//获得类的信息
public class Demo06 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
Class c1 = Class.forName("com.cheng.reflection.User");
?
//获得类的名字:
System.out.println(c1.getName());//获得包名和类名
System.out.println(c1.getSimpleName());//获得类名
?
//获得类的属性:
System.out.println("=====================================");
Field[] fields = c1.getFields();//只能找到public属性
?
fields = c1.getDeclaredFields();//能找到全部属性
for (Field field1 : fields) {
System.out.println(fields);//输出
}
?
//获得指定属性的值
Field field = c1.getDeclaredField("name");
System.out.println(field);
?
//获得类的方法
System.out.println("=====================================");
Method[] methods = c1.getMethods();
for (Method method : methods) {
System.out.println("getmethods:"+methods);//获得本类和父类的全部public方法
}
methods = c1.getDeclaredMethods();
for (Method method : methods) {
System.out.println("getDeclaredMethods"+methods);//获得本类的全部方法,私有方法也可
}
//获得指定方法
//为啥放参数,因为有重载
Method getname = c1.getMethod("getName",null);//方法名参数
Method setname = c1.getMethod("setName",String.class);
System.out.println(getname);
System.out.println(setname);//输出
?
//获得构造器
System.out.println("=========================================");
Constructor[] constructors = c1.getConstructors();
for (Constructor constructor : constructors) {
System.out.println(constructor);
}
constructors = c1.getDeclaredConstructors();
for (Constructor constructor : constructors) {
System.out.println(constructor);
}
?