一.反射机制
框架 = 注解 + 反射 + 设计模式
在程序运行时,在堆内存的方法区中就产生了一个Class类型的对象(一个类只有一个Class对象),这个对象就包含了完整的类的结构信息。我们可以通过这个对象看到类的结构,操作类的属性和方法。
反射机制详解
本质是JVM得到class对象之后,再通过class对象进行反编译,从而获取对象的各种信息。
注意:Java属于先编译再运行的语言,程序中对象的类型在编译期就确定下来了,而当程序在运行时可能需要动态加载某些类,这些类因为之前用不到,所以没有被加载到JVM。通过反射,可以在运行时动态地创建对象并调用其属性,不需要提前在编译期知道运行的对象是谁。
1.反射相关的主要API:
java.lang.Class:代表一个类
java.lang.reflect.Method:代表类的方法
java.lang.reflect.Field:代表类的成员变量
java.lang.reflect.Constructor:代表类的构造器
注意:通过反射可以直接调用该类所在的私有属性和方法。new对象的方法无法直接调用私有的方法和属性,若想调用必须提供公共的外部接口,将私有属性或方法包装起来。
2.关于java.lang.Class类的理解
① 类的加载过程:
程序经过编译(javac.exe)命令以后,会生成一个或多个字节码文件(.class结尾)。接着我们使用运行(java.exe)命令对某个字节码文件进行解释运行。相当于将某个字节码文件加载到内存中。此过程就称为类的加载。加载到内存中的类,我们就称为运行时类,此运行时类就作为Class的一个实例。
② 换句话说,Class的实例就对应着一个加载到内存中的运行时类。
3.获取Class实例的方式
加载到内存中的运行时类,会缓存一定的时间,在此时间内,我们可以通过不同的方式来获取此运行时类。
public class ReflectionTest01 {
@Test
//获取Class实例的方式(加载到内存中的运行时类,会缓存一定的时间,在此时间内,我们可以通过不同的方式来获取此运行时类。前三种需要掌握)
public void test01() throws ClassNotFoundException {
//方式一:调用运行时类的属性
Class clazz1 = Person.class;
System.out.println(clazz1);
//方式二:通过运行时类的对象,调用getClass()
Person person = new Person();
Class clazz2 = person.getClass();
System.out.println(clazz2);
//方式三(最常用):调用Class的静态方法:forName(String className)
Class clazz3 = Class.forName("com.jd.wds.Person");//此处使用"."作为类包的分隔符
//clazz3 = Class.forName("java.lang.String");
System.out.println(clazz3);
//方式四:通过当前的类名使用类的加载器:ClassLoader (了解)
ClassLoader classLoader = ReflectionTest01.class.getClassLoader();
Class clazz4 = classLoader.loadClass("com.jd.wds.Person");
System.out.println(clazz4);
//注意,在运行期间,一个类只有一个Class对象产生,所以打印结果都是true;
System.out.println(clazz1 == clazz2);//引用数据类型"=="判断的是地址值
System.out.println(clazz2 == clazz3);
System.out.println(clazz3 == clazz4);
}
}
4.那些类型作为Class对象
① class:外部类,成员(成员内部类,静态内部类),局部内部类,匿名内部类
② interface:接口
③ []:数组
④ enum:枚举
⑤ annotation:注解@interface
⑥ primitive type:基本数据类型
⑦ void
@Test
//Class类实例可以是那些结构的说明:
public void test02(){
Class c1 = Object.class;
Class c2 = Comparable.class;
Class c3 = String[].class;
Class c4 = int[][].class;
Class c5 = ElementType.class;
Class c6 = Override.class;
Class c7 = int.class;
Class c8 = void.class;
Class c9 = Class.class;
int[] a = new int[10];
int[] b = new int[100];
Class c10 = a.getClass();
Class c11 = b.getClass();
//只要数组类型和维度一致,就是同一个Class
System.out.println(c10==c11);//true
}
5.反射提供的功能:
① 在运行时判断任意一个对象所属的类
② 在运行时构造任意一个类的对象
③ 在运行时判断任意一个类所具有的成员变量和方法
④ 在运行时获取泛型信息
⑤ 在运行时调用任意一个对象的成员变量和方法
⑥ 在运行时处理注解
⑦ 生成动态代理
总结:创建类的对象的方式?
方式一:new +构造器
方式二:要创建Xxx类的对象,可以考虑:Xxx、Xxxs、XxxFactory、XxxBuilder类中查看是否有静态方法的存在。可以调用其静态方法,创建Xxx对象。
方式三:通过反射
//反射测试类
public class ReflectionTest {
@Test
public void test01() throws Exception {
Class clazz = Person.class;
//1.通过反射,创建Person类的对象
Constructor constructor = clazz.getConstructor(String.class,int.class);
Object obj = constructor.newInstance("小王",19);//创建了对应的运行时类的对象(可以强转类型)
Person person = (Person) obj;
System.out.println(person.toString());
//2.通过反射,调用对象的属性、方法
//调用属性
Field age = clazz.getDeclaredField("age");
age.set(person,10);
System.out.println(person.toString());
//调用方法
Method show = clazz.getDeclaredMethod("show");
show.invoke(person);
System.out.println("***********************************");
//通过反射,可以调用Person类中的私有属性、方法
//调用私有的构造器
Constructor constructor1 = clazz.getDeclaredConstructor(String.class);
constructor1.setAccessible(true);
Person person1 = (Person) constructor1.newInstance("小吕");
System.out.println(person1);
//调用私有的属性
Field name = clazz.getDeclaredField("name");
name.setAccessible(true);
name.set(person1,"小杨");
System.out.println(person1);
//调用私有的方法
Method showNation = clazz.getDeclaredMethod("showNation", String.class);
showNation.setAccessible(true);
String str = (String) showNation.invoke(person1,"中国");//相当于person1.showNation("中国")
System.out.println(str);
}
}
class Person{
private String name;
public int age;
public Person() {
}
private Person(String name){
this.name = name;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public void say(){
System.out.println("我是public修饰的say()方法...");
}
private String showNation(String nation){
System.out.println("我的国籍是:"+nation);
return nation;
}
public void show(){
System.out.println("我是public修饰的show()方法...");
}
}
6.使用ClassLoader加载配置文件
@Test
//使用ClassLoader加载配置文件
public void test01() throws Exception{
Properties properties = new Properties();
//读取配置文件方式1:使用流的方式(默认目录module下)
// FileInputStream fis = new FileInputStream("jdbc.properties");
// properties.load(fis);
//读取配置文件方式2:使用类加载器的方式读取配置文件(默认src目录下)
ClassLoader classLoader = ClassLoaderTest.class.getClassLoader();
InputStream stream = classLoader.getResourceAsStream("jdbc1.properties");
properties.load(stream);
String user = properties.getProperty("user");
String password = properties.getProperty("password");
System.out.println("user = "+user+", password = "+password);
System.out.println();
//配置文件存在中文时,出现乱码处理:File | Settings | Editor | File Encodings | Tranparent native-to-ascii conversion(勾选)
}
7.通过反射,创建对应运行时类的对象
@Test
public void test03(){
//Person类必须提供一个空惨的构造器,权限应该是public
Class<Person> person = Person.class;
Person p1 = null;
try {
//newInstance():调用类的无参构造器,创建运行时类的实例
//在javaBean中要求提供一个public的空参构造器。原因:
//1.便于通过反射,创建运行时类的对象
//2.便于子类继承此运行时类时,默认调用super()时,保证父类有此构造器
p1 = person.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
System.out.println(p1);
}
8.体会反射的动态性
public class ExampleTest {
@Test
public void test01(){
for(int i = 10;i<100;i++){
int random = new Random().nextInt(3);
String className = "";
switch (random){
case 1:
className = "java.util.Date";
break;
case 2:
className = "java.lang.Object";
break;
case 3:
className = "com.jd.exer.Cat";
break;
}
try {
Object instance = getInstance(className);
System.out.println(instance);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public Object getInstance(String className) throws Exception {
Class clazz = Class.forName(className);
return clazz.newInstance();
}
}
二.反射的测试实例
//自定义的功能丰富的Person类
@MyAnnotation(value = "hi")
public class Person extends Creature<String> implements Comparable<String>, MyInterface {
private String name;
int id;
public int age;
public Person(){
}
@MyAnnotation(value = "abc")//我们使用的是自定义的注解,并无实际意义
private Person(String name){
this.name = name;
}
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 interest,int age) throws NullPointerException,ClassNotFoundException{
return interest + age;
}
void say(){
System.out.println("每个国家有不同的语言...");
}
@Override
public void info() {
System.out.println("我是一个人...");
}
@Override
public int compareTo(String o) {
return 0;
}
private static void desc(){
System.out.println("我是个可爱的人...");
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", id=" + id +
", age=" + age +
", weight=" + weight +
'}';
}
}
//自定义的接口MyInterface
public interface MyInterface {
void info();
}
//自定义的Person类的父类Creature
public class Creature<T> implements Serializable {
private char gender;
public double weight;
private void breath(){
System.out.println("生物呼吸...");
}
public void eat(){
System.out.println("生物吃东西...");
}
}
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.RUNTIME)
//自定义注解NyAnnotation
public @interface MyAnnotation {
String value() default "hello";//自定义注解(没有实际意义)注解默认值
}
1.获取运行时类的属性和内部结构
//1.获取类的属性结构
@Test
public void test01(){
Class clazz = Person.class;
//getFields():获取当前类及其父类中声明为public的属性(包括父类)
Field[] fields = clazz.getFields();
for(Field f: fields){
System.out.println(f);
}
//getDeclaredFields():获取当前运行时类中声明的所有属性(不包括父类)
System.out.println();
Field[] declaredFields = clazz.getDeclaredFields();
for(Field df: declaredFields){
System.out.println(df);
}
}
//2.获取属性的结构
//权限修饰符 数据类型 变量名 变量值...
@Test
public void test02(){
Class clazz = Person.class;
Field[] declaredFields = clazz.getDeclaredFields();
for(Field f : declaredFields){
//1.权限修饰符
int modifier = f.getModifiers();//获取权限修饰符,返回一个数
System.out.print(Modifier.toString(modifier)+"\t");//转为字符串
//2.数据类型
Class type = f.getType();//getType():获取数据类型
System.out.print(type.getName()+"\t");
//3.变量名
String name = f.getName();
System.out.print(name+"\t");
System.out.println();
}
}
2.获取运行时类的方法结构
@Test
public void test01(){
Class clazz = Person.class;
//getMethods():获取当前运行时类及其所有父类中声明为public权限的方法
Method[] methods = clazz.getMethods();
for(Method m : methods){
System.out.println(m);
}
System.out.println();
//getDeclaredMethods():获取当前运行时类中声明的所有方法(不包括父类中的方法)
Method[] declaredMethods = clazz.getDeclaredMethods();
for(Method dm : declaredMethods){
System.out.println(dm);
}
}
3.获取运行时类的方法的内部结构
/*
@Xxx
权限修饰符 返回值类型 方法名(参数列表)throws Exception{...}
*/
@Test
public void test03(){
Class clazz = Person.class;
Method[] declaredMethods = clazz.getDeclaredMethods();
for(Method dm : declaredMethods){
//1.获取方法声明时的注解
Annotation[] annotations = dm.getAnnotations();
for(Annotation a : annotations){
System.out.println(a);
}
//2.方法的权限修饰符
int modifiers = dm.getModifiers();
System.out.print(Modifier.toString(modifiers)+"\t");
//3.方法返回值类型
Class returnType = dm.getReturnType();
System.out.print(returnType.getName()+"\t");
//4.方法的名称
String name = dm.getName();
System.out.print(name);
System.out.print("(");
//5.方法的形参列表
Class[] parameterTypes = dm.getParameterTypes();
if (parameterTypes!=null && parameterTypes.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[] excepTypes = dm.getExceptionTypes();
if(excepTypes != null && excepTypes.length != 0){
System.out.print("throws ");
for(int i = 0;i<excepTypes.length;i++){
if(i==excepTypes.length-1){
System.out.print(excepTypes[i].getName());
break;
}
System.out.print(excepTypes[i].getName()+",");
}
}
System.out.println();
}
}
4.获取运行时类构造器结构
//1.获取构造器结构
@Test
public void test01(){
Class clazz = Person.class;
//getConstructors():获取当前运行时类的public权限的构造器
Constructor[] constructors = clazz.getConstructors();
for(Constructor c : constructors){
System.out.println(c);
}
System.out.println();
//getDeclaredConstructors():获取当前运行时类中声明的所有权限的构造器
Constructor[] dConstructors = clazz.getDeclaredConstructors();
for(Constructor c : dConstructors){
System.out.println(c);
}
}
5.获取运行时类的父类以及父类的泛型
//2.获取运行时类的父类
@Test
public void test02(){
Class clazz = Person.class;
//获取运行时类的父类
Class superclass = clazz.getSuperclass();
System.out.println(superclass);
}
//3.获取当前类带泛型的父类
@Test
public void test03(){
Class clazz = Person.class;
//获取当前类带泛型的父类
Type genericSuperclass = clazz.getGenericSuperclass();
System.out.println(genericSuperclass);
}
//4.获取运行时类的带泛型的父类的泛型
@Test
public void test04(){
Class clazz = Person.class;
Type genericSuperclass = clazz.getGenericSuperclass();
ParameterizedType paraType = (ParameterizedType) genericSuperclass;
//获取泛型类型
Type[] actualTypeArguments = paraType.getActualTypeArguments();
// System.out.println(actualTypeArguments[0].getTypeName());//java.lang.String
System.out.println(((Class)actualTypeArguments[0]).getName());//java.lang.String
}
6.获取运行时类的接口、所在包、注解等
//1.获取运行时类实现的接口
@Test
public void test05(){
Class clazz = Person.class;
Class[] interfaces = clazz.getInterfaces();
for(Class in : interfaces){
System.out.println(in);
}
System.out.println();
//获取运行时类父类实现的接口
Class[] interfaces1 = clazz.getSuperclass().getInterfaces();
for(Class in : interfaces1){
System.out.println(in);
}
}
//2.获取运行时类所在的包
@Test
public void test06(){
Class clazz = Person.class;
Package aPackage = clazz.getPackage();
System.out.println(aPackage);
//获取运行时类声明的注解
Annotation[] annotations = clazz.getAnnotations();
for(Annotation a: annotations){
System.out.println(a);
}
}
7.调用运行时类的指定属性
@Test
public void test01() throws Exception {
Class clazz = Person.class;
//创建运行时类的对象
Person p = (Person) clazz.newInstance();
//获取指定的属性:获取的属性是public的属性(很少使用,因为属性很少设置为public权限)
Field age = clazz.getField("age");
Field id = clazz.getDeclaredField("id");
//设置当前属性的值
//set(Object obj,Object value):设置obj对象的属性值
age.set(p, 8);
//获取当前属性值
//get(Object obj):获取对象obj的属性值,返回Object类型
int page = (int) age.get(p);
System.out.println(page);
}
//如何操作运行时类指定的属性(要求掌握)
@Test
public void test02() throws Exception {
Class clazz = Person.class;
Person p = (Person)clazz.newInstance();//创建运行时类的对象
//1.getDeclaredField(String name):获取运行时类指定的属性
Field name = clazz.getDeclaredField("name");
//2.保证当前的属性是可访问的
name.setAccessible(true);
//3.设置、获取相应的属性值
name.set(p,"小王");
String names = (String) name.get(p);
System.out.println(names);
}
8.调用运行时类的指定方法
//如何操作运行时类的指定方法
@Test
public void test03() throws Exception{
Class clazz = Person.class;
//创建运行时类的duixisng
Person p = (Person) clazz.newInstance();
//1.获取指定的某个方法:
//getDeclaredMethod():参数1 指明获取方法的名称 参数2 指明获取方法的形参列表
Method show = clazz.getDeclaredMethod("show", String.class);
//2.确保当前的方法可访问
show.setAccessible(true);
//3.调用方法的invoke():参数1:方法的调用者 参数2:给方法形参赋值的实参
//invoke()方法的返回值即为调用的方法的返回值
Object chm = show.invoke(p,"China");//String nation = p.show("China")
System.out.println(chm);
System.out.println("*************如何调用静态方法***************");
Method desc = clazz.getDeclaredMethod("desc");
desc.setAccessible(true);
//如果调用的静态方法没有返回值,则invoke()返回值为null
Object invoke = desc.invoke(Person.class);
System.out.println(invoke);
}
9.调用运行时类的指定构造器
@Test
public void test04() throws Exception{
Class clazz = Person.class;
//1.获取指定的构造器
//getDeclaredConstructor():参数,构造器的参数列表
Constructor constructor = clazz.getDeclaredConstructor(String.class);
//2.确保当前的构造器可访问
constructor.setAccessible(true);
//3.调用构造器创建运行时类的对象
Person p = (Person)constructor.newInstance("小吕");
System.out.println(p);
}
疑问1:通过直接new的方式或反射的方式都可以调用公共的结构,开发中到底用那个?
建议:直接new的方式。
疑问2:何时会使用反射的方式?
在编译的时候不确定要使用哪个类的对象。
如:在访问时浏览器中的服务已经运行,此时根据客户端需要的操作如登录、注册等,我们选择不同的客户端传来的参数,使用反射机制来确定要使用的类的对象。
反射的特征:动态性
疑问3:反射机制与面向对象中的封装性是不是矛盾的?如何看待两个技术?
不矛盾。封装是指将某个类的属性或方法私有化,提示对外提供的公共的属性和方法就可以使用,私有的属性和方法方法就不要使用,对属性可以使用公共的getter/setter方法使用。
反射是指能不能调的问题,只是不建议使用私有的方法和属性,但是要想使用还是可以使用的。