反射概述
Java反射机制:是指在运行时去获取一个类的变量和方法信息。然后通过获取到的信息来创建对象,调用方法的一种机制。由于这种动态性,可以极大的增强程序的灵活性,程序不用在编译期就完成确定,在运行期仍然可以扩展
获取Class类的对象
我们要想通过反射去使用一个类,首先我们需获取到该类的字节码文件对象,也就是类型为Class类型的对象
提供三种方式获取Class类型的对象
- 使用类的class属性来获取该类对应的Class对象。举例:Student.class将会返回Student类对应的Class对象
- 调用对象的getClass()方法,返回该对象所属类对应的Class对象
- 该方法是Object类中的方法,所有的Java对象都可以调用该方法
- 用Class类中的静态方达forName(StringclassName),该方法需要传入字符串参数,该字串参数的值是某个类的全路径,也就是完整包名的路径。
package reflect_01;
public class Student {
//成员变量,一个私有,一个默认,一个公共
private String name;
int age;
public String address;
//构造方法,一个私有,一个默认,两个公共
public Student() {
super();
}
private Student(String name) {
super();
this.name = name;
}
Student(int age, String address) {
super();
this.age = age;
this.address = address;
}
public Student(String name, int age, String address) {
super();
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 reflect_01;
public class reflectDemo {
public static void main(String[] args) throws ClassNotFoundException {
//使用类的class属性来获取该类对应的class对象
Class<Student> c1 = Student.class;
System.out.println(c1);
Class<Student> c2 = Student.class;
System.out.println(c1 == c2);
//调用对象的getClass()方法,返回该对象所属类对应的Class对象
Student s = new Student();
Class<? extends Student> c3 = s.getClass();
System.out.println(c1 == c3);
//使用Class类中的静态方法forName(String className);
Class<?> c4 = Class.forName("reflect_01.Student");
System.out.println(c1 == c4);
}
}
反射获取构造方法并使用
Class类中用于获取构造方法的方法
- Constructor<?>[] getConstructors():返回所有公共构造方法对象的数组
- Constructor<?>[] getDeclaredConstructors():返回所有构造方法对象的数组
- Constructor<T> getConstructor(Class<?>...parameterTypes):返回单个公共构造方法对象
- Constructor<T> getDeclaredConstructor(Class <?>...parameterTypes):返回单个构造方法对象
Constructor类中用于创建对象的方法
- T newlnstance(Object..initargs):根据指定的构造方法创建对象
package reflect_02;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class reflectDemo1 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
//获取Class对象
Class<?> c = Class.forName("reflect_01.Student");//获取字节码文件对象
//Constructor<?>[] getconstructors() 返回一个包含Contructor对象的数组,Constructor对象反映了由该Class对象表示的类的所有公共构造函贸
Constructor<?>[] cons1 = c.getConstructors();
for(Constructor con : cons1) {
System.out.println(con);
//public reflect_01.Student(java.lang.String,int,java.lang.String)
//public reflect_01.Student()
}
//Constructor<>[] getDeclaredConstructors() 返回反映由该Class对象表示的类声明的所有构造函数的Constructor对象的数组
Constructor<?>[] cons2 = c.getDeclaredConstructors();
for(Constructor con : cons2) {
System.out.println(con);
// public reflect_01.Student(java.lang.String,int,java.lang.String)
// reflect_01.Student(int,java.lang.String)
// private reflect_01.Student(java.lang.String)
// public reflect_01.Student()
}
//Constructor(<T> getconstructor(Class<?>... parameterTypes) 返回一个Constructor对象,该对象反映由该Class对象表示的类的指定公共构造函数
//Constructor<T> getDeclaredConstructor (Class<?>... parameterTypes) 返回一个Constructor对象,该对象反映由此class对象表示的类或接口的指定构造函数
//参数:你要获取的构造方法的参数的个数和数据类型对应的字节码文件对象
Constructor<?> cons3 = c.getConstructor();//cons3构造方法对象
//Constructor提供了一个类的单个构造函数的信息和访问权限
//T newInstance(Object...initargs)使用由此Constructor对象表示的构造函数,使用指定的初始化参数来创建和初始化构造函数的声明类的新实例
Object obj = cons3.newInstance();
System.out.println(obj);//Student [name=null, age=0, address=null]
// Student s = new Studen();
// System.out.println(s);
}
}
反射获取构造方法并使用练习
练习1;通过反射实期如下操作
Student s = new Student("林青霞",30,"西安");
System.out.println(s);
基本数据类型也可以根据.class得到对应的Class类型
package reflect_02;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
//反射获取构造方法并使用练习
//练习1;通过反射实期如下操作
//Student s = new Student("林青霞",30,"西安");
//System.out.println(s);
public class reflectDemo2 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
//获取Class对象
Class<?> c = Class.forName("reflect_01.Student");
//public Student(String name, int age, String address)
//Constructor(<T> getconstructor(Class<?>... parameterTypes)
Constructor<?> con = c.getConstructor(String.class, int.class, String.class);
//基本数据类型也可以根据.class得到对应的Class类型
//T newInstance(Object...initargs)
Object obj = con.newInstance("林青霞",30,"西安");
System.out.println(obj);//Student [name=林青霞, age=30, address=西安]
}
}
练习2:通过反射实现如下操作
Students = new Student(“林青霞”);
System.out.println(s);
public void setAccessible(boolean flag):值为true,取消访问检查
package reflect_02;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class reflectDemo3 {
// 练习2:通过反射实现如下操作
// Students = new Student(“林青霞”);
// System.out.println(s);
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, Exception, Exception, IllegalArgumentException, InvocationTargetException {
//获取Class对象
Class<?> c = Class.forName("reflect_01.Student");
//private Student(String name)
//Constructor<T> getDeclaredConstructor (Class<?>... parameterTypes)
Constructor<?> cons = c.getDeclaredConstructor(String.class);
//暴力反射
//public void setAccessible(boolean flag):值为true,取消访问检查
cons.setAccessible(true);
Object obj = cons.newInstance("林青霞");
System.out.println(obj);//Student [name=林青霞, age=0, address=null]
}
}
反射获取成员变量并使用
Class类中用于获取成员变量的方法
Field[] getFields():返回所有公共成员变量对象的数组
Field[] getDeclaredFields():返回所有成员变量对象的数组
Field getField(String name):返回单个公共成员变量对象
Field getDeclaredField(String name):返回单个成员对象
Field类中用于给成员变量赋值的方法
void set(Object obj,Object value):给obj对象的成员变量赋值为value
package reflect_03;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
public class reflectDemo1 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException, NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
//获取Class对象
Class<?> c = Class.forName("reflect_01.Student");
//获取成员变量
//Field[] getFields() 返回一个包含 Field对象的数组, Field对象反映由该 Class对象表示的类或接口的所有可访问的公共字段。
//Field[] getDeclaredFields() 返回一个 Field对象的数组,反映了由该 Class对象表示的类或接口声明的所有字段。
Field[] fs1 = c.getFields();
for(Field f : fs1)
System.out.println(f);//public java.lang.String reflect_01.Student.address
System.out.println("---------------");
Field[] fs2 = c.getDeclaredFields();
for(Field f : fs2)
System.out.println(f);
// private java.lang.String reflect_01.Student.name
// int reflect_01.Student.age
// public java.lang.String reflect_01.Student.address
System.out.println("---------------");
//Field getField(String name) 返回一个 Field对象,该对象反映由该 Class对象表示的类或接口的指定公共成员字段。
//Field getDeclaredField(String name) 返回一个 Field对象,该对象反映由该 Class对象表示的类或接口的指定声明字段。
Field addressField = c.getField("address");//成员变量对象
//获取无参构造方法创建对象
Constructor<?> cons = c.getConstructor();//构造方法对象
Object obj = cons.newInstance();
// obj.addressField = "西安";
// Field提供有关类或接口的单个字段的信息和动态访问。
// void set(Object obj, Object value) 将指定的对象参数中由此 Field对象表示的字段设置为指定的新值。
addressField.set(obj, "西安");//给obj的成员变量addressField赋值为西安
System.out.println(obj);//Student [name=null, age=0, address=西安]
// Student s = new Studen();
// s.address = "西安";
// System.out.println(s);
}
}
反射获取成员变量并使用练习
练习:通过反射实现如下操作
Student s = new Studen();
s.name = "林青霞";
s.age = 30;
s.address = "西安";
System.out.println(s);
package reflect_03;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
//练习:通过反射实现如下操作
//Student s = new Studen();
//s.name = "林青霞";
//s.age = 30;
//s.address = "西安";
//System.out.println(s);
public class reflectDemo2 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException {
// 获取Class对象
Class<?> c = Class.forName("reflect_01.Student");
//Student s = new Studen();
Constructor<?> cons = c.getConstructor();
Object obj = cons.newInstance();
System.out.println(obj);//Student [name=null, age=0, address=null]
//s.name = "林青霞";
Field namefield = c.getDeclaredField("name");
namefield.setAccessible(true);
namefield.set(obj, "林青霞");
//s.age = 30;
Field agefield = c.getDeclaredField("age");
agefield.setAccessible(true);
agefield.set(obj, 30);
//s.address = "西安";
Field addressField = c.getDeclaredField("address");
addressField.setAccessible(true);
addressField.set(obj, "西安");
System.out.println(obj);//Student [name=林青霞, age=30, address=西安]
}
}
反射获取成员方法并使用
Class类中用于获取成员方法的方法
Mcthod[] getMethods():返回所有公共成员方法对象的数组,包括继承的
Method[] getDeclaredMethods():返回所有成员方法对多的数组,不包括继承的
Method getMethod(String name,Class=<?>...parameterTypes):返回单个公共成员方法对象
Method getDeclaredMethod(String name,Class<?>...pararnelelTypes):返回单个成员方法
对象Method类中用于调用成员方法的方法
Object invoke(Object obj,Object...args):调用obj对象的成员方法,参数是args,返回值是Object类型
package reflect_04;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class reflectDemo1 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
//获取Class对象
Class<?> c = Class.forName("reflect_01.Student");
//Method[] getMethods() 返回一个包含 方法对象的数组, 方法对象反映由该 Class对象表示的类或接口的所有公共方法,包括由类或接口声明的对象以及从超类和超级接口继承的类。
//Method[] getDeclaredMethods() 返回一个包含 方法对象的数组, 方法对象反映由 Class对象表示的类或接口的所有声明方法,包括public,protected,default(package)访问和私有方法,但不包括继承方法。
Method[] methods = c.getMethods();
for(Method m : methods) {
System.out.println(m);
}
System.out.println("---------------");
Method[] declaredMethods = c.getDeclaredMethods();
for(Method m : declaredMethods) {
System.out.println(m);
}
//Method getMethod(String name, Class<?>... parameterTypes) 返回一个 方法对象,该对象反映由该 Class对象表示的类或接口的指定公共成员方法。
//Method getDeclaredMethod(String name, Class<?>... parameterTypes) 返回一个 方法对象,它反映此表示的类或接口的指定声明的方法 Class对象。
//public void method1()
Method m = c.getMethod("method1");
//获取无参构造方法构建对象
Constructor<?> cons = c.getConstructor();
Object obj = cons.newInstance();
//obj.m()
//Method在类或接口上提供有关单一方法的信息和访问权限。
//Object invoke(Object obj, Object... args) 在具有指定参数的指定对象上调用此 方法对象表示的基础方法
//Object:返回值类型
//obj:调用方法的对象
//args:方法需要的参数
m.invoke(obj);//method
//Student s = new Studen();
//s.method1();
}
}
反射获取构造方法并使用练习
练习: 通过反射实现如下操作
Student s = new Studen();
s.method1();
s.method2("林青霞");
String ss = s.method3("林青霞",30);
System.out.println(ss);
s.function();
package reflect_04;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
//练习,通过反射实现如下操作
//Student s = new Studen();
//s.method1();
//s.method2("林青霞");
//String ss = s.method3("林青霞",30);
//System.out.println(ss);
//s.function();
public class reflectDemo2 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
// 获取Class对象
Class<?> c = Class.forName("reflect_01.Student");
Constructor<?> cons = c.getConstructor();
Object obj = cons.newInstance();
//s.method1();
Method m1 = c.getMethod("method1");
m1.invoke(obj);//method
//s.method2("林青霞");
Method m2 = c.getMethod("method2", String.class);
m2.invoke(obj, "林青霞");//method林青霞
//String ss = s.method3("林青霞",30);
//System.out.println(ss);
Method m3 = c.getMethod("method3", String.class,int.class);
Object o = m3.invoke(obj, "林青霞",30);
System.out.println(o);//林青霞,30
//s.function();
Method declaredMethod = c.getDeclaredMethod("function");
declaredMethod.setAccessible(true);
declaredMethod.invoke(obj);//function
}
}
反射练习
package reflect_05;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
//练习1:有一个ArrayList<Integer>集合,现在想在这个集合中添加一个字符申数据,如何实现?
public class reflectTest1 {
public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
// 创建集合
ArrayList<Integer> arr = new ArrayList();
arr.add(10);
// arr.add("hello");
Class<? extends ArrayList> c = arr.getClass();
Method m = c.getMethod("add", Object.class);
m.invoke(arr, "hello");
m.invoke(arr, "world");
System.out.println(arr);//[10, hello, world]
}
}
练习2:通过配置文件运行类中的方法
package reflect_05;
import java.io.FileNotFoundException;
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;
// 练习2:通过配置文件运行类中的方法
public class reflectTest2 {
public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
// Study s = new Study();
// s.studyFunc();
// Teacher t = new Teacher();
// t.teach();
/*
* class.txt
* className=xxx
* methodName=xxx
*/
//加载数据
Properties prop = new Properties();
FileReader fr = new FileReader("Test\\class.txt");
prop.load(fr);
fr.close();
/*
* className=reflect_05.Study
methodName=studyFunc
*/
String className = prop.getProperty("className");
String methodName = prop.getProperty("methodName");
//通过反射来使用
Class<?> c = Class.forName(className);//reflect_05.Study
Constructor<?> cons = c.getConstructor();
Object obj = cons.newInstance();
Method m = c.getMethod(methodName);
m.invoke(obj);
}
}