框架的核心和架构师的核心
反射和代理是重中之重
反射
反射的作用
在运行的时候由代码获取类的信息
三种获取类信息的方式:
- 对象.getClass()
- Class.forName("类的路径")
- 类.class
Class :一个用来存储类信息的类
获取类信息是获取的整体的类的信息,类的一切信息。属性的修饰权限,方法的个数、参数、修饰权限等
获取类信息的小例子
// Demo.java
package likou;public class Demo {public int age;private String name;public static int x1;public Demo() {}public Demo(int a,String b) {}public void m1(String xx ,int yy) {}public static void m2(int qq,double kk) {}
}
// Test.java
package likou;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;public class Test {public static void main(String[] args) throws Exception {String name = "likou.Demo";try{Class cl = Class.forName("likou.Demo");Class supercl = cl.getSuperclass();
// 获取修饰符String modifiers = Modifier.toString(cl.getModifiers());if(modifiers.length() >0) {System.out.print(modifiers+" ");}System.out.print("class "+ name);if(supercl != null && supercl != Object.class) {System.out.print(" extends "+supercl.getName());}System.out.print("\n{\n");printConstructors(cl);System.out.println();printMethods(cl);System.out.println();printFields(cl);System.out.println("}");}catch(ClassNotFoundException e){e.printStackTrace();}System.exit(0);}public static void printConstructors(Class cl) {
// 构造方法类ConstructorConstructor[] constructors = cl.getDeclaredConstructors();for(Constructor c : constructors) {String name = c.getName();System.out.print(" ");String modifiers = Modifier.toString(c.getModifiers());if(modifiers.length() > 0) {System.out.print(modifiers + " ");}System.out.print(name+"(");Class[] paramTypes = c.getParameterTypes();for(int j = 0;j<paramTypes.length;j++) {if(j>0) {System.out.print(paramTypes[j].getName());}}System.out.println(");");}}public static void printMethods(Class cl) {Method[] methods = cl.getDeclaredMethods();for(Method m : methods) {Class retType = m.getReturnType();String name = m.getName();System.out.print(" ");String modifiers = Modifier.toString(m.getModifiers());if(modifiers.length() > 0) {System.out.print(modifiers+" ");}System.out.print(retType.getName()+ " " + name +"(");Class[] paramTypes = m.getParameterTypes();for(int j=0;j<paramTypes.length;j++) {if(j>0) {System.out.print(", ");}System.out.print(paramTypes[j].getName());}System.out.println(");");}}public static void printFields(Class cl) {Field[] fields = cl.getDeclaredFields();for(Field f:fields) {Class type = f.getType();String name= f.getName();System.out.print(" ");String modifiers = Modifier.toString(f.getModifiers());if(modifiers.length()>0) {System.out.print(modifiers+ " ");}System.out.println(type.getName()+ " " + name+ ";");}}}