反射

一、概述

1. 反射机制

JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法

对于任意一个对象,都能够调用它的任意方法和属性

这种动态获取信息以及动态调用对象方法的功能称为java语言的反射机制。

 

类类型与类对象:

类是对象的模板,对象是类的实例,

Person p = new Person()

在java中,万事万物皆是对象,如上所示:p是类Person的对象,同样的Person也是Class的对象。

Class cls = Person.class

Person的类对象是cls,cls的类类型是Class。所有java类都继承了Object类,包括Class也是。

2. Class类

2.1 与反射相关的类

Class类   代表类的实体,在运行的Java应用程序中表示类和接口

Field类    代表类的成员变量(成员变量也称为类的属性)

Method类     代表类的方法

Constructor 类   代表类的构造方法

 

Class类:

Class代表类的实体,在运行的Java应用程序中表示类和接口。在这个类中提供了很多有用的方法,这里对他们简单的分类介绍。

2.1 Class获得类相关的方法

asSubclass(Class<U> clazz)    把传递的类的对象转换成代表其子类的对象

Cast   把对象转换成代表类或是接口的对象

getClassLoader()     获得类的加载器

getClasses()       返回一个数组,数组中包含该类中所有公共类和接口类的对象

getDeclaredClasses()   返回一个数组,数组中包含该类中所有类和接口类的对象

forName(String className)   根据类名返回类的对象

getName()   获得类的完整路径名字

newInstance()   创建类的实例

getPackage()   获得类的包

getSimpleName()   获得类的名字

getSuperclass()   获得当前类继承的父类的名字

getInterfaces()   获得当前类实现的类或是接口

2.2 获得类相关的方法

asSubclass(Class<U> clazz)   把传递的类的对象转换成代表其子类的对象

Cast               把对象转换成代表类或是接口的对象

getClassLoader()        获得类的加载器

getClasses()          返回一个数组,数组中包含该类中所有公共类和接口类的对象

getDeclaredClasses()        返回一个数组,数组中包含该类中所有类和接口类的对象

forName(String className)   根据类名返回类的对象

getName()      获得类的完整路径名字

newInstance()      创建类的实例

getPackage()       获得类的包

getSimpleName()      获得类的名字

getSuperclass()   获得当前类继承的父类的名字

getInterfaces()     获得当前类实现的类或是接口

2.3 获得类中属性相关的方法

getField(String name)   获得某个公有的属性对象

getFields()   获得所有公有的属性对象

getDeclaredField(String name)   获得某个属性对象

getDeclaredFields()   获得所有属性对象

2.4 获得类中注解相关的方法

getAnnotation(Class<A> annotationClass)   返回该类中与参数类型匹配的公有注解对象

getAnnotations()   返回该类所有的公有注解对象

getDeclaredAnnotation(Class<A> annotationClass)   返回该类中与参数类型匹配的所有注解对象

getDeclaredAnnotations()   返回该类所有的注解对象

2.5 获得类中构造器相关的方法

getConstructor(Class...<?> parameterTypes)   获得该类中与参数类型匹配的公有构造方法

getConstructors()   获得该类的所有公有构造方法

getDeclaredConstructor(Class...<?> parameterTypes)   获得该类中与参数类型匹配的构造方法

getDeclaredConstructors()   获得该类所有构造方法

2.6 获得类中方法相关的方法

getMethod(String name, Class...<?> parameterTypes)   获得该类某个公有的方法

getMethods()   获得该类所有公有的方法

getDeclaredMethod(String name, Class...<?> parameterTypes)   获得该类某个方法

getDeclaredMethods()   获得该类所有方法

2.7 类中其他重要的方法

isAnnotation()   如果是注解类型则返回true

isAnnotationPresent(Class<? extends Annotation> annotationClass)   如果是指定类型注解类型则返回true

isAnonymousClass()   如果是匿名类则返回true

isArray()   如果是一个数组类则返回true

isEnum()   如果是枚举类则返回true

isInstance(Object obj)   如果obj是该类的实例则返回true

isInterface()     如果是接口类则返回true

isLocalClass()      如果是局部类则返回true

isMemberClass()    如果是内部类则返回true

3. Field类

Field代表类的成员变量(成员变量也称为类的属性)。

equals(Object obj)   属性与obj相等则返回true

get(Object obj)      获得obj中对应的属性值

set(Object obj, Object value) 设置obj中对应属性值

4. Method类

Method代表类的方法。

invoke(Object obj, Object... args)   传递object对象及参数调用该对象对应的方法

5. Constructor类

Constructor代表类的构造方法。

newInstance(Object... initargs) 根据传递的参数创建类的对象。

二、代码 

// 自定义了一个注解,这个注解叫Demo
@Retention(RetentionPolicy.RUNTIME)
@interface Demo {}

class Foo {
    public void testHello() {
        System.out.println("Hello World");
    }

    @Demo
    public void testHellBao() {
        System.out.println("Hello BaoBao");
    }

    @Demo
    @Test //一个方法上面可以访问多个注解
    public void demo() {
        System.out.println("ning");
    }
}

public class Demo2 {
    @SneakyThrows
    public static void main(String[] args) {
        annotationTest();
    }

    /**
     * 注解是利用反射解析并执行的
     */
    private static void annotationTest() throws Exception {
        while (true) {
            String className = "reflect.custom_annotation.Foo";
            //一切反射程序,入口都是:Class
            Class cls = Class.forName(className);
            
            //动态获取所有方法信息
            Method[] methods = cls.getDeclaredMethods();
            Object obj = cls.newInstance();
            
            //要处理每个方法上面的注解,遍历每个方法,处理每个方法上的注解
            for (Method method : methods) {
                System.out.println(method);
                //获取方法上全部的注解
                Annotation[] anns = method.getAnnotations();
                System.out.println(Arrays.toString(anns));
                //查找方法上是否包含指定的注解
                Annotation ann = method.getAnnotation(Demo.class);//该方法返回值为true,false
                System.out.println(ann);

                if (ann != null) {
                    method.invoke(obj);
                }
            }
        }
    }

    /**
     * 测试调用方法
     */
    private static void invokeTest() throws Exception {
//        Scanner in = new Scanner(System.in);
//        System.out.println("输入类名:");
//        String className = in.nextLine();
        String className = "reflect.custom_annotation.Foo";

        // "动态"的加载类到方法区
        Class cls = Class.forName(className); //类的全名就是包名加类名
        System.out.println("类对象:\t" + cls);

        //"动态"创建对象!
        Object obj = cls.newInstance();
        System.out.println("对象:\t" + obj);
        System.out.println("------------------");

        //"动态"获取类上声明的全部方法信息
        //Declared声明的    Method方法
        Method[] methods = cls.getDeclaredMethods();
        for (Method method : methods) {
            System.out.println("\n\t");
            System.out.println("方法全名:\t" + method);
            System.out.println("方法名:\t" + method.getName()); //获取方法名
            if (method.getName().startsWith("test")) {
                System.out.println("test()方法:\t" + method.getName());
                //"动态"的执行方法
                method.invoke(obj);
            }
        }
    }
}

 

参考:

java高级特性 - 反射

posted @ 2020-09-05 22:16  一帘幽梦&nn  阅读(208)  评论(0编辑  收藏  举报
点击查看具体代码内容