反射
将java代码的各个组成部分封装为其他对象,可以在程序运行过程中操作这些对象.
反射的好处:
-
可以在程序运行过程中,操作这些对象。
-
可以解耦,提高程序的可扩展性。
获取Class对象的方式
获取class对象方式 | 作用 | 应用场景 |
---|---|---|
Class.forName("全类名") | 通过指定的字符串路径获取 | 多用于配置文件,将类名定义在配置文件中。读取文件,加载类 |
类名.class | 通过类名的属性class获取 | 多用于参数的传递 |
对象.getClass() | 通过对象的getClass()方法获取 | 多用于对象的获取字节码的方式 |
案例演示 创建一个Student类,获取Student类的class文件对象
public static void main(String[] args)throws Exception{
Student student = new Student();
Class c1 = student.getClass();
System.out.println(c1);
Class c2 = Student.class;
System.out.println(c2);
Class c3 = Class.forName("com.doit.communication.Student");
System.out.println(c3);
}
反射获取构造方法
Class类中与Constructor相关方法
1. Constructor[] getConstructors()
获取所有的public修饰的构造方法
2. Constructor getConstructor(Class... parameterTypes)
根据参数类型获取构造方法对象,只能获得public修饰的构造方法。
如果不存在对应的构造方法,则会抛出 java.lang.NoSuchMethodException 异常。
参数是可变参数,调用此方法时,可以不写参数,获取的空参构造
可以写参数,给定的参数必须是Class对象
比如:
参数 String name,int age
调用此方法: String.class,int.class
Constructor类中常用方法
1. T newInstance(Object... initargs)
根据指定参数创建对象。
2. T newInstance()
空参构造方法创建对象。
获取无参数构造方法
public static void main(String[] args)throws Exception{
Class cla = Class.forName("com.doit.communication.Student");
//获取无参数构造方法
Constructor constructor = cla.getConstructor();
//运行构造方法
Object object = constructor.newInstance();
System.out.println(object);
}
获取有参数构造方法
public static void main(String[] args)throws Throwable{
Class cla = Class.forName("com.doit.communication.Student");
//获取有参数构造方法
Constructor constructor = cla.getConstructor(String.class, int.class);
//运行构造方法,传递实际参数
Object object = constructor.newInstance("张三",20);
System.out.println(object);
}
反射获取构造方法的简单方式
Class类中定义了方法 T newInstance()
,可以直接运行获取到的构造方法。
要求:被反射的类中必须有public权限的无参数构造方法。
public static void main(String[] args)throws Throwable{
Class cla = Class.forName("com.doit.communication.Student");
Object object = cla.newInstance();
System.out.println(object);
}
反射成员方法执行
Class类中与Method相关方法
1. Method[] getMethods()
获取所有的public修饰的成员方法,包括父类中。
2. Method getMethod("方法名", 方法的参数类型... 类型)
根据方法名和参数类型获得一个方法对象,只能是获取public修饰的
Method类中常用方法
Object invoke(Object obj, Object... args)
返回值Object,表示调用方法后,该方法的返回值
根据参数args调用对象obj的该成员方法
如果obj=null,则表示该方法是静态方法
反射获取无参数方法
public static void main(String[] args)throws Throwable{
Class cla = Class.forName("com.doit.communication.Student");
Object object = cla.newInstance();
//获取study方法
Method method = cla.getMethod("study");
//执行方法,传递对象
method.invoke(object);
}
反射获取有参数方法
public static void main(String[] args)throws Throwable{
Class cla = Class.forName("com.doit.communication.Student");
Object object = cla.newInstance();
//获取有参数的方法eat
Method method = cla.getMethod("eat",String.class,double.class);
//调用eat方法,传递实际参数
method.invoke(object,"吃饭",9.9);
}