Java高级--反射

本文详细介绍了Java反射机制,包括通过Class对象获取类信息、创建类实例、访问类属性和方法。此外,还展示了如何通过反射获取注解对象,并提供了相关方法的示例。反射是Java框架设计的核心,能够提升开发效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.什么是反射?

反射是框架设计的灵魂,框架:它是一个半成品,可以拿来使用,添加上自己的业务代码。提高开发效率。

反射就是把类中成员抽取成其他类的过程。这就是反射。

 2.如何获取反射类对象--Class

有三种:

(1) 通过Class.forName获取反射对象.

Class.forName("全路径")
--spring它就是使用的该模式<bean class="全路径">

(2)通过类名.class获取

类名.class;
---代理类--->SqlSession.getMapper(StudentDao.class)

(3) 通过对象.getClass()方法获取

对象.getClass();
---当知道对象时可以通过这种方式获取反射对象
package demo;


public class Test01 {
    public static void main(String[] args) throws ClassNotFoundException {
        //1.通过Class.forName来获取反射类对象。
        Class aClass = Class.forName("demo.People");
        //2.通过类名调用.class获取反射类对象
        Class aClass1 = People.class;
        //3.通过对象获取反射类对象
        People p=new People();
        Class aClass2 = p.getClass();

        //思考:上面三个反射对象的引用地址是否一致! 是一致的。 一个类只会被加在到内存中一次。
        System.out.println(aClass==aClass1);
        System.out.println(aClass2==aClass1);
    }
}

实体类:

package edu;

/**
 * @Author Li Qinghua
 * @Create 2022/7/14 19:03
 */
public class People extends Father{
    private String name;
    public int age;

    public void method(){
        System.out.println(name+" "+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 "People{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}


class Father {
    private int weight;
    public int height;

    public void show(){
        System.out.println(weight+" "+height);
    }
}

3.通过反射类获取对应的类对。

aClass.newInstance();

package demo2;

import demo.People;


public class Test02 {
    public static void main(String[] args) throws IllegalAccessException, InstantiationException {
        //1.获取反射类对象
        Class<People> aClass = People.class;
        //2.由反射类创建类对象---调用为无参构造函数
        People people = aClass.newInstance();
        People people2 = aClass.newInstance();

        //3.他们的地址是否相同
        System.out.println(people==people2);
    }
}

4.通过反射获取对应的Field属性对象

package demo3;

import java.lang.reflect.Field;


public class Test {
    public static void main(String[] args) throws Exception {
        Class<?> aClass = Class.forName("demo.People");

        //获取本类中指定的属性对象
        Field name = aClass.getDeclaredField("name");
        System.out.println(name);
        //获取本类以及父类中指定的属性---必须为public修饰的。
        Field name1 = aClass.getField("sex");
        System.out.println(name1);

        //获取本类中所有的属性对象
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field field:declaredFields) {
            System.out.println(field);
        }

        //获取本类以及父类中所有public修饰的属性对象
        Field[] fields = aClass.getFields();
        for (Field field:
             fields) {
            System.out.println(field);
        }

    }
}

4.2 Field属性对象中常见的方法

getName():获取属性名
setAccessible(true):设置属性可访问。
set(o,v):为对象o的属性赋值v
get(o):获取对象o的属性值
 public static void main(String[] args) throws Exception {
        Class<People> peopleClass = People.class;

        Field nameField = peopleClass.getDeclaredField("name");
        //1.获取属性的名称
        String name = nameField.getName();
        System.out.println("属性名称:"+name);

        //2.为属性赋值.
        //Object obj,对象
        // Object value
        People people = peopleClass.newInstance();
        System.out.println(people);

        nameField.setAccessible(true);//为nameField设置可访问权限,打破了封装性
        nameField.set(people,"张三");
        System.out.println(people);

        //3.获取属性值
        Object o = nameField.get(people);
        System.out.println(o);

        //nameField.getAnnotation();//获取nameField属性上的注解对象
    }

5.通过反射获取对应的Method方法对象

同上原理

package demo3;

import demo.People;

import java.lang.reflect.Method;


public class Test03 {
    public static void main(String[] args) throws Exception {
        Class<People> aClass = People.class;

        //获取本类中所有的方法。
        Method[] declaredMethods = aClass.getDeclaredMethods();
        for (Method method:declaredMethods) {
            System.out.println(method);
        }


        System.out.println("======================================================");
        //获取本类和父类中所有public修饰的方法
        Method[] methods = aClass.getMethods();
        for (Method method : methods) {
            System.out.println(method);
        }

        System.out.println("**************************************************************");
        //本类中指定的 方法对象
        Method fun = aClass.getDeclaredMethod("fun");
        System.out.println(fun);
        Method setName = aClass.getDeclaredMethod("setName",String.class);
        System.out.println(setName);

        //获取本类以及父类中指定名称的方法对象
        Method equals = aClass.getMethod("equals", Object.class);
        System.out.println(equals);

    }
}

5.1 Method类中常见的方法

package edu.demo05;

import edu.People;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Author Li Qinghua
 * @Create 2022/7/14 19:42
 */
public class Test {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        Class<People> aClass = People.class;

        Method setName = aClass.getDeclaredMethod("setName", String.class);
        People people = aClass.newInstance();
        Object invoke = setName.invoke(people, "李四");
        Method setAge = aClass.getDeclaredMethod("setAge", int.class);
        Object invoke1 = setAge.invoke(people, 22);
        System.out.println(people);
    }
}

6. 获取相应注解对象

自定义一个注解

package edu.demo06;


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(value = {ElementType.TYPE,ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface StudentAnnotation {
    String value();
    int nums();
}

实体类:

package edu.demo06;

/**
 * @Author Li Qinghua
 * @Create 2022/7/14 19:48
 */
@StudentAnnotation(value = "student",nums = 1)
public class Student {
    @StudentAnnotation(value = "name",nums = 2)
    private String name;

    @StudentAnnotation(value = "age",nums = 2)
    private Integer age;

    @StudentAnnotation(value = "method",nums = 3)
    private int method(){
        System.out.println("哈哈哈");
        return 1;
    }
}

测试:

package edu.demo06;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @Author Li Qinghua
 * @Create 2022/7/14 19:49
 */
public class TestStudent {
    public static void main(String[] args) throws NoSuchMethodException, NoSuchFieldException {
        Class<Student> aClass = Student.class;

        StudentAnnotation annotation = aClass.getAnnotation(StudentAnnotation.class);
        String value = annotation.value();
        int nums = annotation.nums();
        System.out.println(value+" "+nums);

        Field name = aClass.getDeclaredField("name");
        StudentAnnotation nameAnnotation = name.getAnnotation(StudentAnnotation.class);
        System.out.println(nameAnnotation.value()+" "+nameAnnotation.nums());

        Field age = aClass.getDeclaredField("age");
        StudentAnnotation ageAnnotation = age.getAnnotation(StudentAnnotation.class);
        System.out.println(ageAnnotation.value()+" "+ageAnnotation.nums());


        Method method = aClass.getDeclaredMethod("method");
        StudentAnnotation methodAnnotation = method.getAnnotation(StudentAnnotation.class);
        System.out.println(methodAnnotation.value()+" "+methodAnnotation.nums());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值