一、反射
1.1 类对象和类的对象
类对象:类加载的产物,封装了一个类的所有信息(类名、父类、接口、属性、方法等) 类的对象:一个类的实例对象
1.2 获取类对象的三种方式
Student s = new Student ( ) ;
Class c = s. getClass ( ) ;
Class c = 类名. class ;
通过静态方法Class.forName()获取类对象
Class c = Class. forName ( "包名.类名" ) ;
1.3 常用方法
getName();获取类名 getPackage();获取包名 getSuperclass();获取父类 getInterfaces();获取父接口 getFields();获取属性 getMethods();获取方法 getConstructors();获取构造器 newInstance();获取实例对象
1.4 反射应用场景
public static void main ( String[ ] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException,
IllegalAccessException, InstantiationException {
Class< Student> c = Student. class ;
Field field = c. getDeclaredField ( "name" ) ;
Student stu = c. newInstance ( ) ;
field. setAccessible ( true ) ;
field. set ( stu, "张三" ) ;
System. out. println ( field. get ( stu) ) ;
}
public static void main ( String[ ] args) throws NoSuchMethodException, SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException, InstantiationException {
Class< Teacher> c = Teacher. class ;
Method method = c. getMethod ( "hello" , String. class , int . class ) ;
Teacher teacher = c. newInstance ( ) ;
method. invoke ( teacher, "张三" , 30 ) ;
}