反射的概述
是指在运行时去获取一个类的变量和方法信息。然后通过获取到的信息来创建对象,调用方法的一种机制。 由于这种动态性,可以极大的增强程序的灵活性,程序不用在编译期就完成确定,在运行期仍然可以扩展
获取Class类对象的三种方式
类名.class属性
对象名.getClass()方法
Class.forName(全类名)方法
package com.itxuexi.it24.Reflect01;
import static java.lang.Class.forName;
public class ReflectDemo01 {
public static void main(String[] args) throws ClassNotFoundException {
//使用类的class属性来获取该类对应的Class对象 --最简单
Class<Student> c1 = Student.class;
System.out.println(c1); //class com.itxuexi.it24.Reflect01.Student
Class<Student> c2 = Student.class;
System.out.println(c1 == c2); //true
System.out.println("-------------------------");
//调用对象的getClass()方法,返回该对象所属类对应的Class对象
Student s = new Student();
Class<? extends Student> c3 = s.getClass();
System.out.println(c1 == c3); //true
System.out.println("---------------------");
//使用Class类中的静态方法forName(String className) --最灵活
Class<?> c4 = Class.forName("com.itxuexi.it24.Reflect01.Student");
System.out.println(c1 == c4);
}
}
反射获取构造方法并使用
Class类获取构造方法对象的方法:
Constructor[] getConstructors() 返回所有公共构造方法对象的数 组
Constructor[] getDeclaredConstructors() 返回所有构造方法对象的数组
Constructor getConstructor(Class… parameterTypes) 返回单个公共构造方法对象
Constructor getDeclaredConstructor(Class… parameterTypes) 返回单个构造方法对象
package com.itxuexi.it24.Reflect02;
import com.itxuexi.it24.Reflect01.Student;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class ReflectDemo01 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
//获取Class对象
Class<?> c = Class.forName("com.itxuexi.it24.Reflect01.Student");
//Constructor<?>[] getConstructors() 返回一个包含 Constructor对象的数组,Constructor对象反映了由该 Class对象表示的类的所有公共构造函数
// 数组;public 只能拿到公共的方法
Constructor<?>[] cons1 = c.getConstructors();
//Constructor<?>[] getDeclaredConstructors() 返回反映由该 Class对象表示的类,声明的所有构造函数的 Constructor对象的数组
//数组;所有的构造方法
Constructor<?>[] cons2 = c.getDeclaredConstructors();
//cons1或cons2
for (Constructor con : cons2) {
System.out.println(con);
}
System.out.println("--------------------------");
//返回单个公共构造方法对象
Constructor<?> cc = c.getConstructor();
//返回单个构造方法对象
Constructor<?> dd = c.getDeclaredConstructor();
System.out.println(cc);
System.out.println(dd);
System.out.println("------------------------");
Constructor提供了一个类的单个构造函数的信息和访问权限
//获取单个的构造方法
Constructor<?> con = c.getConstructor(); //无参
Object obj = con.newInstance();
System.out.println(obj);
//同上
Student s = new Student();
System.out.println(s);
}
}
Constructor类用于创建对象的方法
T newInstance(Object…initargs):根据指定的构造方法创建对象
反射获取构造方法并使用练习
//通过反射获取公共的构造方法并创建对象
package com.itxuexi.it24.Reflect03;
public class Student {
//成员变量:一个私有,一个默认,一个公共
private String name;
int age;
public String address;
//构造方法 :一个私有,一个默认,两个公共
public Student() {
}
private Student(String name) {
this.name = name;
}
Student(String name, int age) {
this.name = name;
this.age = age;
}
public Student(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
//成员方法: 一个私有,四个公共
private void function() {
System.out.println("function");
}
public void method1() {
System.out.println("method");
}
public void method2(String s) {
System.out.println("method:" +s);
}
public String method3(String s,int i) {
return s + "," + i;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", address='" + address + '\'' +
'}';
}
}
//---------------------------------------------------------------
package com.itxuexi.it24.Reflect03;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class ReflectDemo02 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
//
Class<?> c = Class.forName("com.itxuexi.it24.Reflect03.Student");
// public Student(String name, int age, String address) {
Constructor<?> con = c.getConstructor(String.class,int.class,String.class);
//
Object obj = con.newInstance("林青霞", 30, "西安");
System.out.println(obj);
}
}
//通过反射获取私有构造方法并创建对象
package com.itxuexi.it24.Reflect03;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class ReflectDemo03 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
//获取Class对象
Class<?> c = Class.forName("com.itxuexi.it24.Reflect03.Student");
//private Student(String name)
//Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
Constructor<?> con = c.getDeclaredConstructor(String.class);
//IllegalAccessException 私有方法创建对象;暴力反射,值为true,取消访问检查
con.setAccessible(true);
Object obj = con.newInstance("林青霞");
System.out.println(obj);
}
}
反射获取成员变量并使用
Class类获取成员变量对象的方法
Field[] getFields() 返回所有公共成员变量对象的数组
Field[] getDeclaredFields() 返回所有成员变量对象的数组
Field getField(String name) 返回单个公共成员变量对象
Field getDeclaredField(String name) 返回单个成员变量对象
package com.itxuexi.it24.Reflect03;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
public class ReflectChenDemo01 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException {
Class<?> c = Class.forName("com.itxuexi.it24.Reflect03.Student"); //01
//所有可访问的公共字段
Field[] fields1 = c.getFields(); //public
//所有字段
Field[] fields2 = c.getDeclaredFields(); //private, ,public
for (Field field : fields2) {
System.out.println(field);
}
System.out.println("-----------------------------");
//指定公共成员字段 address
Field addressField = c.getField("address"); //02
//获取无参构造方法创建对象
Constructor<?> con = c.getConstructor(); //
Object obj = con.newInstance();
addressField.set(obj,"西安"); // //给obj的成员变量addressField赋值为西安 //03
System.out.println(obj);
}
}
Field类用于给成员变量赋值的方法
voidset(Object obj,Object value) 给obj对象的成员变量赋值为value
练习
package com.itxuexi.it24.Reflect03;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
public class ReflectChenDemo02 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
//获取Class对象
Class<?> c = Class.forName("com.itxuexi.it24.Reflect03.Student");
// 无参构造方法创建对象 Student s = new Student(); // 无论公共私有统一用 getConstructor,setAccessible(true)
Constructor<?> con = c.getConstructor();
Object obj = con.newInstance();
System.out.println(obj);
Field nameField = c.getDeclaredField("name");
nameField.setAccessible(true);
nameField.set(obj,"林青霞");
System.out.println(obj);
Field ageField = c.getDeclaredField("age");
ageField.setAccessible(true);
ageField.set(obj,20);
System.out.println(obj);
Field addressField = c.getDeclaredField("address");
addressField.setAccessible(true);
addressField.set(obj,"西安");
System.out.println(obj);
}
}
/*
Student{name='null', age=0, address='null'}
Student{name='林青霞', age=0, address='null'}
Student{name='林青霞', age=20, address='null'}
Student{name='林青霞', age=20, address='西安'}
*/
反射获取成员变量成员方法并使用
Class类获取成员方法对象的方法
Method[] getMethods() 返回所有公共成员方法对象的数组,包 括继承的
Method[] getDeclaredMethods() 返回所有成员方法对象的数组,不包括 继承的
Method getMethod(String name, Class… parameterTypes) 返回单个公共成员方法对象
Method getDeclaredMethod(String name, Class… parameterTypes) 返回单个成员方法对象
package com.itxuexi.it24.Reflect03;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectMethodDemo01 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
//获取Class对象
Class<?> c = Class.forName("com.itxuexi.it24.Reflect03.Student"); //01
//该 Class对象表示的类或接口的所有公共方法,包括由类或接口声明的对象以及从超类和超级接口继承的类
Method[] methods1 = c.getMethods();
// 方法对象反映由Class对象表示的类或接口的所有声明方法,不含继承;
Method[] methods2 = c.getDeclaredMethods();
for (Method method : methods2) {
System.out.println(method);
}
System.out.println("--------------------");
//返回单个公共成员方法对象
Method m = c.getMethod("method1"); //02
Constructor<?> con = c.getConstructor();
Object obj = con.newInstance();
//调用obj对象的成员方法,参数是args,返回值是Object类型
m.invoke(obj); //03
}
}
练习
package com.itxuexi.it24.Reflect03;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectMethodDemo02 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
//获取Class对象
Class<?> c = Class.forName("com.itxuexi.it24.Reflect03.Student");
//Student s = new Student()
Constructor<?> con = c.getConstructor();
Object obj = con.newInstance();
///s.method1();
Method m1 = c.getMethod("method1");
m1.invoke(obj);
//s.method2("林青霞");
Method m2 = c.getMethod("method2", String.class);
m2.invoke(obj,"林青霞");
//String ss = s.method3("林青霞",30);
Method m3 = c.getMethod("method3", String.class, int.class);
Object o = m3.invoke(obj,"林青霞", 30);
System.out.println(o);
//s.function
Method m4 = c.getDeclaredMethod("function");
m4.setAccessible(true);
m4.invoke(obj);
}
}
练习
反射练习之越过泛型检查
反射:可以实现一些正常情况下不能实现的事情;如可以访问类的私有成员
案例需求:通过反射技术,向一个泛型为Integer的集合中添加一些字符串数据
package com.itxuexi.it24.ReflectEx;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
//通过反射技术,向一个泛型为Integer的集合中添加一些字符串数据
public class ReflectEx01 {
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
ArrayList<Integer> array = new ArrayList<>();
array.add(10);
// array.add("hello"); 报错
Class<? extends ArrayList> c = array.getClass();
Method m = c.getMethod("add", Object.class);
m.invoke(array,"hello");
m.invoke(array,"world");
m.invoke(array,"class");
System.out.println(array);
}
}
运行配置文件中指定类的指定方法
package com.itxuexi.it24.ReflectEx;
//ReflectEx02 中文件
public class Student {
public void study(){
System.out.println("好好学习,天天向上");
}
}
//---------------------
package com.itxuexi.it24.ReflectEx;
public class Teacher {
public void teach(){
System.out.println("教书");
}
}
//-----------------------
//class.txt文件
className=com.itxuexi.it24.ReflectEx.Student
methodName=study
//---------------------
package com.itxuexi.it24.ReflectEx;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;
public class ReflectEx02 {
public static void main(String[] args) throws IOException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, ClassNotFoundException {
//
Student s = new Student();
s.study();
//加载数据
Properties prop = new Properties();
FileReader fr = new FileReader("idea_demo\\class.txt");
prop.load(fr);
fr.close();
String className = prop.getProperty("className");
String methodName = prop.getProperty("methodName");
System.out.println(className);
//通过反射来使用
Class<?> c = Class.forName(className); //
Constructor<?> con = c.getConstructor();
Object obj = con.newInstance();
Method m = c.getMethod(methodName); //study
m.invoke(obj);
}
}