示?
public class Test08 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
Class<?> aClass = Class.forName("com.fl.reflection.User");
System.out.println("获取类的名称===========================================================================");
System.out.println(aClass.getName()); //获得包名+类名
System.out.println(aClass.getSimpleName()); //获得类名
System.out.println("获取类的属性===========================================================================");
Field[] fields = aClass.getFields(); //只能找到public属性
for (Field field : fields) {
System.out.println(field);
}
Field[] declaredFields = aClass.getDeclaredFields(); //找到全部属性
for (Field declaredField : declaredFields) {
System.out.println(declaredField);
}
System.out.println("获取指定属性===========================================================================");
Field name = aClass.getDeclaredField("name");
System.out.println(name);
System.out.println("获取类的方法===========================================================================");
Method[] methods = aClass.getMethods(); //获得本类及其父类的全部public方法
for (Method method : methods) {
System.out.println("getMethods:"+method);
}
methods = aClass.getDeclaredMethods(); //获得本类的所有方法
for (Method method : methods) {
System.out.println("getDeclaredMethods:"+method);
}
System.out.println("获得指定的方法*******************************************************************************");
Method getName = aClass.getMethod("getName", null);
Method setName = aClass.getMethod("setName", String.class);
System.out.println(getName);
System.out.println(setName);
System.out.println("获得类的构造器*******************************************************************************");
Constructor<?>[] constructors = aClass.getConstructors();
for (Constructor< ? > constructor : constructors) {
System.out.println("getConstructors:"+constructor);
}
constructors=aClass.getDeclaredConstructors();
for (Constructor< ? > constructor : constructors) {
System.out.println("getDeclaredConstructors:"+constructor);
}
System.out.println("获得指定的构造器*******************************************************************************");
Constructor<?> declaredConstructor = aClass.getDeclaredConstructor(String.class, int.class, int.class);
System.out.println(declaredConstructor);
}
}