zoukankan      html  css  js  c++  java
  • 关于java里面的反射机制

    反射

      反射在每个面向对象的编程语言中都存在,它的主要目的就是在运行时分析类或者对象的状态,导出或提取出关于类、方法、属性、参数等的详细信息,包括注释。 反射是操纵面向对象范型中元模型的 API,可用于构建复杂,可扩展的应用。反射在日常的 Web 开发中其实用的不多,更多的是在偏向底层一些的代码中,比如说框架的底层中依赖注入、对象池、动态代理、自动获取插件列表、自动生成文档以及一些设计模式等等,都会大量运用到反射技术。

    注意:反射可以获取private类型的类实例和对象。这是和普通用法的最大区别。

    在日常开发中反射最终目的主要两个:

      • 创建实例
      • 反射调用方法

     反射的具体用法:

    package com.example.demo.Reflection;
    
    import java.lang.reflect.Constructor;
    import java.lang.reflect.Field;
    import java.lang.reflect.Method;
    
    import static javafx.scene.input.KeyCode.T;
    
    
    public class Test {
        public static void main(String[] args) throws Exception {
    
            //获取公私属性
    
            Field age = Student.class.getField("age");
            Field name = Student.class.getDeclaredField("name");
    
            name.setAccessible(true);
    
            String s = name.get(new Student()).toString();
            int i = (int) age.get(new Student());
    
            System.out.printf("name="+s+";age="+i+"
    ");
    
            //获取公私方法
    
            Student.class.getMethod("hello").invoke(new Student());
    
            Method h = Student.class.getDeclaredMethod("hei", String.class);
            h.setAccessible(true);
            String xiaoming = h.invoke(new Student(), "xiaoming").toString();
            System.out.printf(xiaoming+"
    ");
    
    
            //私有构造方法获取实例
            Constructor<Student> declaredConstructor = Student.class.getDeclaredConstructor(String.class);
    
            declaredConstructor.setAccessible(true);
    
            Student lili = declaredConstructor.newInstance("lili"); //获取构造方法的实例
    
            System.out.printf(name.get(lili).toString());
        }
    }
    
    class Student  {
    
        public int age = 0;
        private String name = "none";
    
        public Student(){
    
        }
        private Student(String name){
            this.name = name;
        }
    
        public void hello() {
            System.out.println("hello");
        }
    
        public String hei(String word) {
    
            return word;
        }
        private int hei(int a) {
            return a;
        }
    }
    暗夜之中,才见繁星;危机之下,暗藏转机;事在人为,为者常成。
  • 相关阅读:
    670. Maximum Swap
    653. Two Sum IV
    639. Decode Ways II
    636. Exclusive Time of Functions
    621. Task Scheduler
    572. Subtree of Another Tree
    554. Brick Wall
    543. Diameter of Binary Tree
    535. Encode and Decode TinyURL
    博客园自定义背景图片
  • 原文地址:https://www.cnblogs.com/zenghansen/p/14717305.html
Copyright © 2011-2022 走看看