反射的使用

class Person{


    static final int c = 2;

    static int b = 200;


    public Person(){

    }

    public Person(String name){
        this.name = name;
    }

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    private void test(){}

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                '}';
    }
}

加载器

		//获取系统类加载器
        ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
        System.out.println("systemClassLoader = " + systemClassLoader);

        //获取系统类加载器的父类,扩展类加载器
        ClassLoader parent = systemClassLoader.getParent();
        System.out.println("parent = " + parent);

        //获取扩展类加载器的父类,根加载器
        ClassLoader parent1 = parent.getParent();

        System.out.println("parent1 = " + parent1);
        System.out.println(parent1.getParent());

        //获取当前类的加载器
        ClassLoader classLoader = Class.forName("com.zhwl.web.core.jhsign.Test").getClassLoader();
        System.out.println(classLoader);


        //获取JDK内部类的加载器
        ClassLoader classLoader1 = Class.forName("java.lang.Object").getClassLoader();
        System.out.println(classLoader1);

反射

		Class c1 = Class.forName("com.zhwl.web.core.jhsign.Person");

        System.out.println(c1.getName());//获取类的全部名称,包括包名
        System.out.println(c1.getSimpleName());//获取类的名称
        Field[] fields = c1.getFields();//获取类的public属性
        for (Field field : fields) {
            System.out.println(field);
        }

        fields = c1.getDeclaredFields();//获取类的所有属性
        for (Field field : fields) {
            System.out.println(field);
        }
        System.out.println("---------------------------------");
        Method[] methods = c1.getMethods();//获取自己和父类的public方法
        for (Method method : methods) {
            System.out.println(method);
        }
        System.out.println("---------------------------------");
        methods = c1.getDeclaredMethods();//获取类本身的所有方法
        for (Method method : methods) {
            System.out.println(method);
        }
        System.out.println("---------------------------------");
        Method setName = c1.getMethod("setName", String.class);//获取指定方法
        System.out.println(setName);
        System.out.println("---------------------------------");
        Constructor[] constructors = c1.getConstructors();//获取所有public的构造方法
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }
        System.out.println("---------------------------------");
        constructors = c1.getDeclaredConstructors();//获取所有的构造方法
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }
        System.out.println("---------------------------------");
        Constructor constructor = c1.getConstructor(null);//获取指定的构造方法
        System.out.println(constructor);

动态创建对象执行方法

		Class c1 = Class.forName("com.zhwl.web.core.jhsign.Person");

        Person o = (Person) c1.newInstance();//构造一个对像,使用此方法Person类必须有无参构造函数
        System.out.println(o);

        System.out.println("-------------------------------------------");
        //通过反射使用构造器创建一个对象
        Constructor constructor = c1.getDeclaredConstructor(String.class);
        Person person = (Person) constructor.newInstance("人类");
        System.out.println(person);
        System.out.println("-------------------------------------------");

        //通过反射获取方法,执行方法
        Method setName = c1.getMethod("setName", String.class);
        //invoke 激活的意思,第一个参数是这个方法的对象,第二个是值,后面可以有多个参数
        setName.invoke(person,"测试");
        System.out.println(person);

        Method test = c1.getDeclaredMethod("test",String.class);
        //关闭安全检查,true为关闭,默认为false打开,如果不关闭安全检查则不能执行private方法
        //Field,Method,Constructor 都有setAccessible方法,setAccessible是打开和禁用安全检查的开关
        //提高代码反射的效率,如果代码中必须使用反射,而该句代码需要频繁的被使用,那么请设置为true
        test.setAccessible(true);
        test.invoke(person,"test");

性能对比分析

	public static void test1(){
        Person p = new Person();
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 1000000000; i++) {
            p.getName();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("普通方式测试" + (endTime - startTime) + "ms");
    }

    public static void test2() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        Person p = new Person();
        Class c = p.getClass();

        Method getName = c.getDeclaredMethod("getName");
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 1000000000; i++) {
            getName.invoke(p,null);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("反射方式测试" + (endTime - startTime) + "ms");
    }

    public static void test3() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        Person p = new Person();
        Class c = p.getClass();

        Method getName = c.getDeclaredMethod("getName");
        getName.setAccessible(true);
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 1000000000; i++) {
            getName.invoke(p,null);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("关闭检测测试" + (endTime - startTime) + "ms");
    }

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException {
        test1();
        test2();
        test3();
    }

普通方式测试8ms
反射方式测试3957ms
关闭检测测试1520ms

获取泛型信息:

public static void test01(Map<String,Person> map, List<Person> list){
        System.out.println("test01");
    }

    public static Map<String,Person> test02(){
        System.out.println("test02");
        return null;
    }

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException {
        Class c1 = Class.forName("com.zhwl.web.core.jhsign.Test");
        Method test01 = c1.getDeclaredMethod("test01", Map.class, List.class);

        //ParmeterTypes 表示一种参数化类型,比如Collection<String>
        Type[] genericParameterTypes = test01.getGenericParameterTypes();//获取泛型参数类型
        for (Type genericParameterType : genericParameterTypes) {
            System.out.println("#" + genericParameterType);
            if(genericParameterType instanceof ParameterizedType){
                //获取真实的参数类型,泛型信息
                Type[] actualTypeArguments = ((ParameterizedType) genericParameterType).getActualTypeArguments();
                for (Type actualTypeArgument : actualTypeArguments) {
                    System.out.println(actualTypeArgument);
                }
            }
        }
        System.out.println("--------------------------------------------");
        Method test02 = c1.getDeclaredMethod("test02", null);
        Type genericReturnType = test02.getGenericReturnType();//获取返回值类型
        if(genericReturnType instanceof ParameterizedType){
            Type[] actualTypeArguments = ((ParameterizedType) genericReturnType).getActualTypeArguments();//获取真实的泛型类型
            for (Type actualTypeArgument : actualTypeArguments) {
                System.out.println(actualTypeArgument);
            }
        }
    }

获取注解信息:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableTest{
    String value();
}

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldTest{

    String columnName();

    String type();

    int length();
}

@TableTest("db_student")
class Student{

    @FieldTest(columnName = "db_id",type = "int",length = 11)
    private int id;

    @FieldTest(columnName = "db_age",type = "int",length = 11)
    private int age;

    @FieldTest(columnName = "db_name",type = "varchar",length = 11)
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, NoSuchFieldException {

        Class c1 = Class.forName("com.zhwl.web.core.jhsign.Student");

        //获取类的所有注解(不包含类里属性的注解)
        Annotation[] annotations = c1.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }
        System.out.println("------------------------------------------");
        //获取注解的类对象,(强转一下类型)
        TableTest tableTest = (TableTest)c1.getAnnotation(TableTest.class);
        String value = tableTest.value();
        System.out.println(value);

        System.out.println("------------------------------------------");

        //获取属性的注解和注解里的值
        Field id = c1.getDeclaredField("id");
        FieldTest fieldTest = (FieldTest)id.getAnnotation(FieldTest.class);
        System.out.println(fieldTest);
        System.out.println(fieldTest.columnName());
        System.out.println(fieldTest.length());
        System.out.println(fieldTest.type());

    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值