第十二节 Java 反射机制
1. 反射机制概述
1.1 Java Reflection
(1)Reflection(反射)是被视为动态语言的关键,反射机制允许程序在执行期借助于Reflection API取得任何类的内部信息,并能直接操作任意类对象的内部属性及方法
(2)加载完类之后,在堆内存的方法区中就产生了一个Class类型的对象(一个类只有一个Class对象),这个对象就包含了完整的类的结构信息。我们可以通过这个对象看到类的结构。这个对象就像一面镜子,透过这个镜子看到类的结构,所以,我们形象的称之为:反射
动态特性:编译的时候还不能确定构造哪个类的对象,只有运行的时候才能确定下来。
使用普通方法和反射对比示例:
public class Person {
private String name;
public int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
private Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void show(){
System.out.println("你好我是Tom");
}
private String showNation(String nation){
System.out.println("我的国籍是:"+nation);
return nation;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class relfectiondemo {
//反射之前,对于Person类的操作
@Test
public void test1(){
//1.创建Person类的对象
Person p1=new Person("Tom",12);
//2. 通过对象调用内部属性和方法
p1.age=10;
System.out.println(p1.toString());
p1.show();
// 在Person 外部,不可以通过Person类的对象调用内部私有结构
}
//反射之后,对于Person类的操作
@Test
public void test2() throws Exception{
Class clazz=Person.class;
//通过反射去创建Person类的对象
Constructor cons=clazz.getConstructor(String.class,int.class);
Object obj=cons.newInstance("Tom",12);
Person p=(Person)obj;
System.out.println(p.toString());
//2.通过反射来调用指定属性和方法
//调属性
Field age = clazz.getDeclaredField("age");
age.set(p,10);
System.out.println(p.toString());
//调用方法
Method show = clazz.getDeclaredMethod("show");
show.invoke(p);
//通过反射是可以调用Person类的私有结构。比如:私有的构造器、方法、属性
System.out.println("******************************************");
Constructor cons1=clazz.getDeclaredConstructor(String.class);
cons1.setAccessible(true);
Person p1=(Person)cons1.newInstance("Jerry");
System.out.println(p1);
//调用私有的属性和方法
Field name = clazz.getDeclaredField("name");
name.setAccessible(true);
name.set(p1,"LiuShuai");
System.out.println(p1);
System.out.println("调用私有的方法");
Method showNation=clazz.getDeclaredMethod("showNation", String.class);
showNation.setAccessible(true);
String nation=(String) showNation.invoke(p1,"China");
System.out.println(nation);
}
}
两个疑问:
(1)通过new 的方式或反射的方式都可以调用公共的结构,开发中用哪个?
//建议用直接new 的方式,
//那么什么时候用反射?这就要看反射的方式、反射的特征:动态性。
如果编译的时候我们可以确定下来new哪个对象,我们就用new 的方式。如果编译的时候我们不确定new哪个,我们就用反射的方式。
比如我们客户端给服务器端去发送数据,我们服务器端是要先跑起来的,这时候我们如果客户端给我们发送Login对象,我们就可以动态的来创建Login对象,如果给我发register对象我们就可以创建register对象。
(2)反射机制与面向对象中的封装性是不是矛盾,如何看待两个技术?
不矛盾。封装性解决的是建议你去调什么的问题,而反射解决的是我能不能调的问题
2. 理解Class类并获取Class实例
2.1 java.lang.Class里面的Class类
- 类的加载过程:程序经过javac.exe命令以后,会生出来一个或多个字节码文件(.class结尾),接着使用java.exe命令对某个字节码文件进行解释运行。相当于将某个字节码文件加载到内存,加载到内存中的这个过程就叫类的加载。加载到内存中的类就称为运行时类,此运行时类就作为Class的一个实例。
- 换句话说,Class的实例就对应着一个运行时类。
- 加载到内存中的运行时类,会缓存一定的时间,在此时间内,我们可以通过不同的方式来获取此运行时类。
创建方式如下:
@Test
public void test3() throws ClassNotFoundException {
//获取Class的实例
//方式一:调用运行时类的属性 .class
// Class<Person> clazz1=Person.class;
Class clazz1=Person.class;
System.out.println(clazz1);
//方式二:通过运行时类的对象,调用getClass()方法
Person p1=new Person();
Class clazz2=p1.getClass();
System.out.println(clazz2);
// 方式三:调用Class类的静态方法,forName(String classPath)
// (主要使用这个方法,因为他更好的体现动态性)
Class clazz3=Class.forName("reflection.Person");
// Class clazz3=Class.forName("java.lang.String");
System.out.println(clazz3);
System.out.println(clazz1==clazz2);//true
System.out.println(clazz1==clazz3);//true 都是运行时类的内存地址
//方法四:使用类的加载器 ClassLoader
ClassLoader classLoader=Relfectiondemo.class.getClassLoader();
Class clazz4=classLoader.loadClass("reflection.Person");
System.out.println(clazz1==clazz4);
}
3. 类的加载与ClassLoader的理解
使用static{ m=30;} 和static int m=100这两个方法进行赋值时,谁在后面显示谁。
如下代码:
public class ClassLoaderTest {
@Test
public void test1(){
//对于自定义类,使用系统类加载器进行加载
ClassLoader classLoader1 = ClassLoaderTest.class.getClassLoader();
System.out.println(classLoader1);
//调用系统类加载器的getParent():获取扩展类加载器
ClassLoader classLoader2 = classLoader1.getParent();
System.out.println(classLoader2);
//调用扩展类加载器的getParent():无法获取引导类加载器
//引导类加载器主要负责核心类库的加载,无法加载自定义类的
ClassLoader classLoader3 = classLoader2.getParent();
System.out.println(classLoader3);
ClassLoader classLoader4 = String.class.getClassLoader();
System.out.println(classLoader4);
}
}
效果如下:
用ClassLoader来读取配置文件:
public void test2() throws IOException {
Properties pros=new Properties();
//读取配置文件的方式一
//这种读取方式的相对路径默认是在当前的moudle下,
// FileInputStream fis=new FileInputStream("jdbc.properties");
// pros.load(fis);
//读取文件的方式二
//这种读取方式相对路径默认是在当前moulde的src下
ClassLoader classLoader1 = ClassLoaderTest.class.getClassLoader();
InputStream is = classLoader1.getResourceAsStream("jdbc1.properties");
pros.load(is);
String user=pros.getProperty("user");
String pwd=pros.getProperty("password");
System.out.println("用户名是:"+user+"\r\n"+"密码是:"+pwd);
}
}
4. 创建运行时类的对象
体现动态性代码:
public class NewInstanceTest {
//通过反射创建对应的运行时类的对象
@Test
public void test1() throws IllegalAccessException, InstantiationException {
Class clazz=Person.class;
/*newInstance():调用此方法,创建运行时类的对象。
* 内部调用了运行时类的的空参的构造器。
*
* 要想用此方法正常的去创建运行时类的对象,要求
* (1)运行时类必须提供空参的构造器
* (2)空参构造器要有足够的的访问权限。通常设置为public。
*
* 在javabean中要求提供一个public的空参构造器。原因:
* (1)便于通过反射,创建运行时类的对象
* (2)便于子类继承此运行时类时,默认调用super()时,保证父类有此构造器
* */
Person obj = (Person)clazz.newInstance();
System.out.println(obj);
}
@Test
public void test2(){
int num= new Random().nextInt(3);//0,1,2
String classPath="";
switch (num){
case 0:
classPath="java.util.Date";
break;
case 1:
classPath="java.lang.Object";
break;
case 2:
classPath="Person";
break;
}
try {
Object obj=getInstance(classPath);
System.out.println(obj);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
/*
* 创建一个指定类的对象
* classPath:指定类的全类名
* */
public Object getInstance(String classPath) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
Class clazz = Class.forName(classPath);
return clazz.newInstance();
}
}
5. 获取运行时类的完整结构
5.1 创建类的结构与获取属性结构
public class Creatuer<T> implements Serializable {
private char gender;
public double weight;
private void breath(){
System.out.println("生物呼吸");
}
public void eat(){
System.out.println("生物吃东西");
}
}
@MyAnnotation(value = "hi")
public class Person extends Creatuer<String> implements Comparable<String>,MyInterface{
private String name;
int age;
public int id;
public Person(){
}
@MyAnnotation(value = "abc")
public Person(String name){
this.name=name;
}
public Person(String name,int age){
this.name=name;
this.age=age;
}
@MyAnnotation
private String show(String nation){
System.out.println("我的国籍是:"+nation);
return nation;
}
public String display(String interests){
return interests;
}
@Override
public int compareTo(String o) {
return 0;
}
@Override
public void info() {
System.out.println("我是一个人");
}
}
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.RUNTIME)//这里必须是RUNTIME才可以反射,SOURCER不可以
public @interface MyAnnotation {
String value() default "hello";
}
public interface MyInterface {
void info();
}
public class FieldTest {
@Test
public void test1(){
Class clazz=Person.class;
//获取属性结构
//getFields():获取当前运行时类及其父类声明中为public访问权限的属性
Field[] fields=clazz.getFields();
for (Field f:fields){
System.out.println(f);
}
//getDeclaredFields():获取当前运行时类中声明的所有属性(不包含父类中声明的属性)
Field[] declaredFields=clazz.getDeclaredFields();
for (Field f:declaredFields){
System.out.println(f);
}
}
5.2 获取方法结构
public class MethodTest {
/*
获取运行时类的方法结构
*/
@Test
public void test1(){
Class clazz=Person.class;
//getMethods():获取当前运行时类及其父类的当中所有声明为public权限的方法
Method[] methods = clazz.getMethods();
for (Method m:methods){
System.out.println(m);
}
//getDeclaredMethods():获取当前运行时类中声明的所有方法。(不包含父类中声明的)
Method[] declaredMethods = clazz.getDeclaredMethods();
for(Method m:declaredMethods){
System.out.println(m);
}
}
@Test
public void test2(){
/*
@Xxxx
权限修饰符 返回值类型 方法名(参数类型1 形参1,...) throws XxxException{}*/
//1.获取方法声明的注解
Class clazz=Person.class;
Method[] declaredMethods = clazz.getDeclaredMethods();
for(Method m:declaredMethods){
Annotation[] annos = m.getAnnotations();
for (Annotation a:annos){
System.out.println(a);
}
//2.权限修饰符
System.out.print(Modifier.toString(m.getModifiers())+"\t");
//3.返回值类型
System.out.print(m.getReturnType().getName()+"\t");
//4. 方法名
System.out.print(m.getName()+"\t");
System.out.print("(");
//5.形参列表
Class[] parameterTypes = m.getParameterTypes();
if(!(parameterTypes==null&¶meterTypes.length==0)){
for (int i=0;i<parameterTypes.length;i++){
if(i==parameterTypes.length-1){
System.out.print(parameterTypes[i].getName()+"args_"+i);
break;
}
System.out.print(parameterTypes[i].getName()+"args_"+i+",");
}
}
System.out.print(")");
//6.抛出的异常
Class[] exceptionTypes = m.getExceptionTypes();
if(!(exceptionTypes==null&&exceptionTypes.length==0)){
System.out.print("throws ");
for(int i=0;i<exceptionTypes.length;i++){
if(i==exceptionTypes.length-1){
System.out.println(exceptionTypes[i].getName());
break;
}
System.out.println(exceptionTypes[i].getName()+",");
}
}
}
}
}
框架=注解+反射+设计模式
5.3 获取构造器结构和获取运行时类的父类以及接口和注解
public class OtherTest {
/*获取构造器结构*/
@Test
public void test1(){
Class clazz=Person.class;
//getConstructors():获取当前运行时类中,声明为public的构造器
Constructor[] constructors = clazz.getConstructors();
for (Constructor c:constructors){
System.out.println(c);
}
//getDeclaredConstructors():获取当前运行时类中声明的所有的构造器
Constructor[] declaredConstructors = clazz.getDeclaredConstructors();
for (Constructor c:declaredConstructors){
System.out.println(c);
}
}
}
@Test
public void test2(){
/*获取运行时类的父类*/
Class clazz=Person.class;
Class superclass = clazz.getSuperclass();
System.out.println(superclass);
}
@Test
public void test3(){
/*获取运行时类的带泛型的父类*/
Class clazz=Person.class;
Type genericSuperclass = clazz.getGenericSuperclass();
System.out.println(genericSuperclass);
//获取运行时类的带泛型的父类的泛型类型
ParameterizedType paramType=(ParameterizedType) genericSuperclass;
Type[] actualTypeArguments = paramType.getActualTypeArguments();
// System.out.println(actualTypeArguments[0].getTypeName());
System.out.println(((Class)actualTypeArguments[0]).getName());
}
@Test
public void test4(){
/*获取运行时类实现的接口*/
Class clazz=Person.class;
Class[] interfaces = clazz.getInterfaces();
for (Class c:interfaces){
System.out.println(c);
}
System.out.println();
//获取运行时类的父类实现的接口
Class[] interfaces1 = clazz.getSuperclass().getInterfaces();
for (Class c:interfaces1){
System.out.println(c);
}
}
@Test
public void test5(){
//获取运行时类所在的包
Class clazz=Person.class;
Package aPackage = clazz.getPackage();
System.out.println(aPackage);
}
@Test
public void test6(){
//获取运行时类声明的注解
Class clazz=Person.class;
Annotation[] annotations = clazz.getAnnotations();
for(Annotation a:annotations){
System.out.println(a);
}
}
}
这里也可以用和获取方法结构类似的去获取构造器权限修饰符等等
6. 调用运行时类的指定结构
public class RedfectionTest {
/**
* 调用运行时类中指定的结构:属性、方法、构造器
*/
@Test
public void testField() throws Exception {
Class clazz=Person.class;
//创建运行时类的对象
Person p=(Person)clazz.newInstance();
//获取指定的属性:要求运行时类中属性声明为public
//通常不采用这种方式
Field id = clazz.getField("id");
//设置当前属性值
id.set(p,1001);//参数1:指定是哪个对象的属性值,参数2:值为多少
//获取当前属性的值,参数1:获得哪个对象的属性值
int pId=(int)id.get(p);
System.out.println(pId);
}
@Test
public void testField1() throws Exception{
Class clazz=Person.class;
//创建运行时类的对象
Person p=(Person)clazz.newInstance();
// getDeclaredField("name"):获取运行时类中指定变量名的属性
Field name = clazz.getDeclaredField("name");
//保证当前属性是可以访问的
name.setAccessible(true);
name.set(p,"Tom");
System.out.println(name.get(p));
}
@Test
public void testMethod() throws Exception{
Class clazz=Person.class;
//创建运行时类的对象(非静态要想访问,必须要有)
Person p=(Person)clazz.newInstance();
//获取指定的某个方法
// getDeclaredMethod():参数1:指明获取的方法名称, 参数2:指明获取的 方法的形参列表
Method show = clazz.getDeclaredMethod("show", String.class);
//保证当前方法是可访问的
show.setAccessible(true);
//invoke():参数1:方法的调用者 参数2:给方法形参赋值的实参
//invoke()的返回值即为对应类中调用的方法的返回值
String china = (String)show.invoke(p, "China");
System.out.println(china);
System.out.println("**************如何调用静态方法********************");
Method showDesc = clazz.getDeclaredMethod("showDesc");
showDesc.setAccessible(true);
//如果调用的方法没有返回值,则invoke()方法返回null
Object invoke = showDesc.invoke(clazz);//这里的clazz,也可以直接换成null,因为这方法是静态的
System.out.println(invoke);
}
@Test
public void testConstructor() throws Exception {
/*如何调用运行时类中的指定的构造器*/
Class clazz=Person.class;
//获取指定的构造器
//getDeclaredConstructor():参数:指明构造器的参数列表
Constructor constructor = clazz.getDeclaredConstructor(String.class);
//保证此构造器可以访问
constructor.setAccessible(true);
//调用此构造器创建运行时类的对象
Person tom = (Person)constructor.newInstance("Tom");
System.out.println(tom);
}
}