4.反射机制(2)

本文深入探讨了Java反射机制,包括Person类的构造器、属性和方法的测试,以及如何获取父类、泛型信息、接口、包和注解等。通过一系列@Test注解的测试方法,展示了如何在运行时动态获取和操作类的元信息,这对于理解和使用Java反射机制至关重要。

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

1.Person类

package com.qiku.reflection2;

/**
 * 2022/6/8 19:52
 *
 * @author yrc
 * @version JavaSE
 */
public class Person extends  Creature<String> implements Comparable<String>,MyInterface{
    private String name;
    int age;
    public  int id;
    public Person(){

    }
    @MyAnnotation(value ="1111")
    public Person(String name){
        this.name=name;
    }
    Person(String name,int age){
        this.name=name;
        this.age=age;
    }
@MyAnnotation(value ="nation")
    private String show(String nation){
        System.out.println("我的国籍是"+nation);
        return  nation;
    }
    private String display(String insterests){
        return  insterests;
    }

    @Override
    public int compareTo(String o) {
        return 0;
    }

    @Override
    public void info() {
        System.out.println("我是一个人");
    }
}

 2.接口和注解以及生物类

package com.qiku.reflection2;

/**
 * 2022/6/8 19:55
 *
 * @author yrc
 * @version JavaSE
 */
public interface MyInterface
{
    void  info();
}
package com.qiku.reflection2;

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

/**
 * 2022/6/8 20:05
 *
 * @author yrc
 * @version JavaSE
 */
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    String value() default "hello";
}
package com.qiku.reflection2;

import java.io.Serializable;

/**
 * 2022/6/8 19:52
 *
 * @author yrc
 * @version JavaSE
 */
public class Creature<T> implements Serializable {
    //Serializable序列化给我们提供了一种技术,用于保存对象的变量。以便于传输。
    // 虽然也可以使用别的一些方法实现同样的功能,但是java给我们提供的方法使用起来是非常方便的。
    //序列化:对象的寿命通常随着生成该对象的程序的终止而终止,有时候需要把在内存中的各种对象的状态(
    // 也就是实例变量,不是方法)保存下来,并且可以在需要时再将对象恢复。虽然你可以用你自己的各种各
    // 样的方法来保存对象的状态,但是Java给你提供一种应该比你自己的好的保存对象状态的机制,那就是序列化。
    //
    //总结:Java 序列化技术可以使你将一个对象的状态写入一个Byte 流里(系列化),并且可以从其它地
    // 方把该Byte 流里的数据读出来(反序列化)。
    private char gender;
    public double weight;
    private  void breath(){
        System.out.println("生物呼吸");
    }
    public void eat(){
        System.out.println("生物吃肉");
    }

}

3.属性测试

package com.qiku.reflection2;

import org.junit.Test;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * 2022/6/8 20:36
 *
 * @author yrc
 * @version JavaSE
 */
public class FieldTest {
    //运行时类的属性结构

    //获取树形结构
    @Test
    public  void test01(){
        Class clazz = Person.class;
        //getFields() 能够获取当前运行时类机器父类中声明为public的 访问权限的属性
        Field[] fields = clazz.getFields();
        for (Field field:fields){
            System.out.println(field);
        }
        //getDeclaredFields()  获取当前运行时类中声明的所有属性 不包含父类中的属性
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field field1:declaredFields){
            System.out.println(field1);
        }
    }
    //权限修饰符 数据类型  变量名
    @Test
    public void test02(){
        Class clazz = Person.class;
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field f:declaredFields){
            System.out.println(f);
            //1 权限修饰符
            int modifiers = f.getModifiers();
            System.out.println(modifiers);
            //获取相应权限类型
            System.out.println(Modifier.toString(modifiers));
            System.out.println("--------");

            //2 数据类型
            Class type=f.getType();
            System.out.println(type.getName());
            System.out.println("------------");

            //变量名
            String name = f.getName();
            System.out.println(name);
            System.out.println();

        }

    }



}

4.方法测试

package com.qiku.reflection2;

import org.junit.Test;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * 2022/6/8 21:03
 *
 * @author yrc
 * @version JavaSE
 */
public class MethodTest {
    //获取 运行时类的方法结构

    @Test
    public void test01(){
        Class<Person> clzz = Person.class;
        //getMethods() 获取父类的public()  权限的方法方法
        Method[] methods = clzz.getMethods();
        for(Method method : methods){
            System.out.println(method);
        }

        // getDeclaredMethods() 获取当前类中生命的所有方法 不包含弗雷德
        Method[] declaredMethods = clzz.getDeclaredMethods();

        for(Method method1 : declaredMethods){
            System.out.println(method1);
        }
    }
    //获取注解
    @Test
    public void test02(){
        Class<Person> clzz = Person.class;
        Method[] declaredMethods = clzz.getDeclaredMethods();
// 获取发方法声明的注解
        for(Method m : declaredMethods){
            Annotation[] annotations = m.getAnnotations();
            for (Annotation annotation :annotations){
                System.out.println(annotation);
            }  //权限修饰符
            System.out.println(Modifier.toString(m.getModifiers()));
            System.out.println();
            //返回值类型
            System.out.println(m.getReturnType());
            System.out.println();
            //方法名
            System.out.println(m.getName());
            System.out.print("(");
            //形参列表
            Class[] parameterTypes = m.getParameterTypes();
            if (!(parameterTypes==null &&parameterTypes.length==0)){
                for ( Class p :parameterTypes){
                    System.out.println(p.getName());
                }
            }
            System.out.print(")");

            //抛出的异常
            Class[] exceptionTypes = m.getExceptionTypes();

            if (exceptionTypes.length>0){
                System.out.println("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()+" , ");
                }
            }
            System.out.println();
        }



    }
}

5.其他测试

package com.qiku.reflection2;

import org.junit.Test;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
* 2022/6/8 21:49
*
* @author yrc
* @version JavaSE
*/
public class OtherTest {
    @Test
    public void test01(){
        Class clzz = Person.class;
        //获取 当前运行时类声明为public的构造器
        Constructor[] constructors = clzz.getConstructors();
        for (Constructor c:constructors){
            System.out.println(c);
        }
        //获取 当前运行时类中 所有的构造器 不包含 父类中的构造器
        Constructor[] declaredConstructors = clzz.getDeclaredConstructors();
        for (Constructor c:declaredConstructors){
            System.out.println(c);
        }
    }
    //获取运行时类的 父类
    @Test
    public void test02(){
        Class clzz = Person.class;
        Class superclass = clzz.getSuperclass();
        System.out.println(superclass);

    }
    //获取带泛型的父类
    @Test
    public void test03(){
        Class clzz = Person.class;
        Type genericSuperclass = clzz.getGenericSuperclass();
        System.out.println(genericSuperclass);
    }
    //获取运行时类的带泛型的父类的泛型     功能性代码 重要!!!!!!!!!!!!!!!!!
    @Test
    public void test04() {
        Class clzz = Person.class;
        Type genericSuperclass = clzz.getGenericSuperclass();
        ParameterizedType parameterizedType=(ParameterizedType) genericSuperclass;

        //获取泛型类型
        Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
        System.out.println(actualTypeArguments[0]);
    }
    //获取运行时类所实现的接口
    @Test
    public void test05() {
        Class clzz = Person.class;

        Class[] interfaces = clzz.getInterfaces();
        for (Class c: interfaces){
            System.out.println(c);
        }

        //获取运行时类的父类的接口  重要 !!!动态代理中可能会用
        Class[] interfaces1 = clzz.getSuperclass().getInterfaces();
        for (Class c: interfaces1){
            System.out.println(c);
        }

    }
    // 获取运行时类的包
    @Test
    public void test06() {
        Class clzz = Person.class;
        Package aPackage = clzz.getPackage();
        System.out.println(aPackage);
    }
//获取运行时类生命的注解
    @Test
    public void test07() {
        Class clzz = Person.class;
        Annotation[] annotations = clzz.getAnnotations();
        for (Annotation annotation:annotations){
            System.out.println(annotation);
        }

    }
}

6.获取指定的属性方法和构造器的使用(重要)

package com.qiku.reflection2;

import org.junit.Test;

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

/**
 * 2022/6/9 14:04
 *
 * @author yrc
 * @version JavaSE
 */
public class ReflectionTest02 {
    //调用运行时类的指定结构:属性 方法 和构造器

    @Test
    public void test01() throws NoSuchFieldException, InstantiationException, IllegalAccessException {
        Class clazz = Person.class;
        Field id = clazz.getField("id");
 Person p= (Person) clazz.newInstance();
        id.set(p,1001);
        int pid = (int) id.get(p);

    }
    //如何操作运行时类的指定属性  ----------需要掌握!!
    @Test
    public void testField1() throws InstantiationException, IllegalAccessException, NoSuchFieldException {
    Class clazz = Person.class;
    //获取运行时类的指定属性。
    Person p=(Person) clazz.newInstance();

        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();

        //获取指定的某个方法    参数一: 获取方法的名称   参数2:知名获取方法的形参列表
        Method show = clazz.getDeclaredMethod("show", String.class);
        show.setAccessible(true);
        /*
        invoke 参数一:方法的调用者 参数2:给方法形参复制的实参
        invoke() 的返回值即为对应类中调用方法的返回值
         */
        show.invoke(p,"CHINA");

    }
    //  需要掌握
    @Test
    public void testStaticMethod() throws Exception {
        System.out.println("----------如何使用静态方法-----------------");
        Class clazz = Person.class;
        Person p=(Person) clazz.newInstance();
        Method showDesc = clazz.getDeclaredMethod("showDesc");
        showDesc.setAccessible(true);
        //如果调用运行时类中的方法没有返回值 则此invoke返回null

        Object invoke = showDesc.invoke(Person.class);
        System.out.println(invoke);//null

    }
    //如何调用 运行时类的 指定构造器
    @Test
    public  void testGetSpecifyCons() throws Exception {
        Class clazz= Person.class;
        // 1 ,获取指定的构造器

        Constructor declaredConstructor = clazz.getDeclaredConstructor(String.class);

        //保证构造器可以访问
        declaredConstructor.setAccessible(true);

        Person pr=(Person)declaredConstructor.newInstance("yooo");
        System.out.println(pr);

    }



}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值