反射机制定义及应用场景
- 定义
反射机制是在JVM运行时动态的去加载某个类,并且对于任意的类都可以去调用其所有属性和方法。 - 应用场景
关于反射机制的应用场景,作者本人的理解是当A类未开发完全,而此时B类需要调用A类,那么此时可以使用反射机制 - 缺点
使用反射机制会消耗一定的系统资源,并且会破坏类的封装性。
获取类的三种方法及利弊
获取类有三种方法,如下所示,其中三种方式中,第一种对象都有了还要反射干什么,第二种需要导入类包,依赖太强,不导包就抛编译错误。一般都使用第三种,一个字符串可以传入也可以写在配置文件中等多种方法。
package com.example.se.reflection;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* @Author:苏平超
* @Description:
* @ate:Createdin 2020/5/26 11:21
*/
public class Test {
public static void main(String[] args) {
//第一种方法
Student stu1=new Student();
Class cla1=stu1.getClass();
System.out.println(cla1.getName());
//第二种方法
try{
Class cla=Student.class;
Student stu=(Student)cla.newInstance();
Field nameField=cla.getDeclaredField("name");
nameField.setAccessible(true);
nameField.set(stu,"jack");
System.out.println(stu.getName());
Method method=cla.getMethod("printinfo",null);
method.invoke(stu,null);
//Object o=method.invoke(stu,null);
//System.out.println(o);
}catch(Exception e){
e.printStackTrace();
}
//第三种方法
try{
Class cla2=Class.forName("com.example.se.reflection.Student");
System.out.println(cla2.getName());
}catch(Exception e){
e.printStackTrace();
}
}
}
Filed类
1、Field[] fs=c.getFields();
//获得公有属性(只能是公有的)/*/可以是父类的公有的属性
2、Field[] fs2=c.getDeclaredFields();
//获得所有属性(全部类型的修饰符属性均可获得)
3、Field fs3=c.getField(String FieldName);
//获得指定名字的公有属性(只能是公有的)
4、Field fs4=c.getDeclaredField(String FieldName);
//获得指定名字的属性(全部类型的修饰符的属性中指定名字)
类加载器
this.getClass().getClassLoader().getResource("template");
调用对象的getClass()方法是获得对象当前的类类型,这部分数据存在方法区中,而后在类类型上调用getClassLoader()方法是得到当前类型的类加载器,我们知道在Java中所有的类都是通过加载器加载到虚拟机中的,而且类加载器之间存在父子关系,就是子知道父,父不知道子,这样不同的子加载的类型之间是无法访问的(虽然它们都被放在方法区中),所以在这里通过当前类的加载器来加载资源也就是保证是和类类型同一个加载器加载的。