Reflection java反射源码分析

这篇具有很好参考价值的文章主要介绍了Reflection java反射源码分析。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Reflection 源码分析

定义

Java的反射(reflection)机制是指在程序的运行状态中,可以构造任意一个类的对象,可以了解任意一个对象所属的类,可以了解任意一个类的成员变量和方法,可以调用任意一个对象的属性和方法。这种动态获取程序信息以及动态调用对象的功能称为Java语言的反射机制。反射被视为动态语言的关键

Class对象

  • Class对象是JVM生成用来保存对象的类的信息的。Java程序执行之前需要经过编译、加载、链接和初始化这几个阶段,编译阶段会将源码文件编译为.class字节码文件,编译器同时会在.class文件中生成Class对象,加载阶段通过JVM内部的类加载机制,将Class对象加载到内存中。在创建对象实例之前,JVM会先检查Class对象是否在内存中存在,如果不存在,则加载Class对象,然后再创建对象实例,如果存在,则直接根据Class对象创建对象实例。JVM中只有一个Class对象,但可以根据Class对象生成多个对象实例。

  • 获取Class对象的三种方式

    • 1.Class.forName方式 传全限定类名

      public class Cat {
          private int age;
          private String name;
      
          public static void main(String[] args) throws ClassNotFoundException {
              Class<?> c1 = Class.forName("org.yrdm.ch1.Cat");
              System.out.println(c1);
          }
      }
      
      结果:
          class org.yrdm.ch1.Cat
      
      1. 调用类实例对象的getClass()方法,继承于Object类的getClass()方法
      public class Cat {
          private int age;
          private String name;
      
          public static void main(String[] args) {
              Cat cat=new Cat();
              Class c1 = cat.getClass();
              System.out.println(c1);
          }
      }
      
      结果:
          class org.yrdm.ch1.Cat
      
    • 3.通过类名 .class

      public class Cat {
          private int age;
          private String name;
      
          public static void main(String[] args) {
              Class c1 = Cat.class;
              System.out.println(c1);
          }
      }
      
      结果:
          class org.yrdm.ch1.Cat
      
  • Class类源码分析文章来源地址https://www.toymoban.com/news/detail-433391.html

    //泛型类
    public final class Class<T> implements java.io.Serializable,GenericDeclaration,Type,AnnotatedElement {
    	//重要方法
        //获取Class对象 static修饰
        @CallerSensitive
        public static Class<?> forName(String className)
                    throws ClassNotFoundException {
            Class<?> caller = Reflection.getCallerClass();
            return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
        }
                                      
        //创建实例,直接调用无参构造进行构造 jdk9后被弃用,使用class.getDeclaredConstructor().newInstance()代替
        @CallerSensitive
        @Deprecated(since="9")
        public T newInstance()
            throws InstantiationException, IllegalAccessException
        {...}
        
        //每个结构都有这四件套 getXXX()  getXXXs()  getDealaredXXX()  getDeclaredXXXs()
        //1.属性
        //根据参数获取属性 public 属性
        @CallerSensitive
        public Field getField(String name){...}
        
        //获取所有public属性,返回属性数组
        @CallerSensitive
        public Field[] getFields() throws SecurityException {
            ...
        }
        
        //Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object.  获取所有属性,public protected default private
        @CallerSensitive
        public Field[] getDeclaredFields() throws SecurityException {
            ...
        }
        
        //Returns a Field object that reflects the specified declared field of the class or interface represented by this Class object.
        @CallerSensitive
        public Field getDeclaredField(String name)
            throws NoSuchFieldException, SecurityException {
            ...
        }
        
        
        //2.获取方法
        //(1).getMethod  name为方法名,因为重载的缘故根据后面的可变长参数来指定特定的方法
        @CallerSensitive
        public Method getMethod(String name, Class<?>... parameterTypes)
            throws NoSuchMethodException, SecurityException {
            ...
        }
        //(2).getMethods()
        @CallerSensitive
        public Method[] getMethods() throws SecurityException {
            ...
        }
        //(3)getDeclaredMethods()
        @CallerSensitive
        public Method[] getDeclaredMethods() throws SecurityException {
            。。。
        }
        //(4).getDeclaredMethod()
        @CallerSensitive
        public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
            throws NoSuchMethodException, SecurityException {
            ...
        }
        
        //3.获取构造函数
         @CallerSensitive
        public Constructor<T> getConstructor(Class<?>... parameterTypes)
            throws NoSuchMethodException, SecurityException
        {
            
        }
        
        @CallerSensitive
        public Constructor<?>[] getConstructors() throws SecurityException {
            
        }
        
        @CallerSensitive
        public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
            throws NoSuchMethodException, SecurityException
        {
           ...
        }
        
        @CallerSensitive
        public Constructor<?>[] getDeclaredConstructors() throws SecurityException {
            
        }
        
        //4.获取所实现的接口
        public Class<?>[] getInterfaces() {
            ...
        }
        
        public Type[] getGenericInterfaces() {
            
        }
        
        //5.获取父类
        public Type getGenericSuperclass() {
            ...
        }
        
        //6.获取注解
        public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
           
        }
    
        public Annotation[] getAnnotations() {
            return AnnotationParser.toArray(annotationData().annotations);
        }
        
        public <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass) {
            Objects.requireNonNull(annotationClass);
    
            return (A) annotationData().declaredAnnotations.get(annotationClass);
        }
        
        public Annotation[] getDeclaredAnnotations()  {
            return AnnotationParser.toArray(annotationData().declaredAnnotations);
        }
        
        //7.获取类中定义的类和嵌套接口
        @CallerSensitive
        public Class<?>[] getClasses() {
            ...
        }
        
        @CallerSensitive
        public Class<?>[] getDeclaredClasses() throws SecurityException {
            SecurityManager sm = System.getSecurityManager();
            if (sm != null) {
                checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), false);
            }
            return getDeclaredClasses0();
        }
        
        //8.获取当前类的加载器
        @CallerSensitive
        @ForceInline // to ensure Reflection.getCallerClass optimization
        public ClassLoader getClassLoader() {
            ClassLoader cl = getClassLoader0();
            if (cl == null)
                return null;
            SecurityManager sm = System.getSecurityManager();
            if (sm != null) {
                ClassLoader.checkClassLoaderPermission(cl, Reflection.getCallerClass());
            }
            return cl;
        }
        
        //9.其他
        public Module getModule() {
            return module;
        }
        
        public String getName() {
            String name = this.name;
            return name != null ? name : initClassName();
        }
        
        public Package getPackage() {
            if (isPrimitive() || isArray()) {
                return null;
            }
            ClassLoader cl = getClassLoader0();
            return cl != null ? cl.definePackage(this)
                              : BootLoader.definePackage(this);
        }
        
        public String getPackageName() {
            ...
        }
        //Finds a resource with a given name.
        @CallerSensitive
        public URL getResource(String name) {
            ...
        }
        
        @CallerSensitive
        public InputStream getResourceAsStream(String name) {}
        
    }
    

URL类

  • Class.getResource() 返回URL类
public final class URL implements java.io.Serializable {
	/**
     * The protocol to use (ftp, http, nntp, ... etc.) .
     * @serial
     */
    private String protocol;

    /**
     * The host name to connect to.
     * @serial
     */
    private String host;

    /**
     * The protocol port to connect to.
     * @serial
     */
    private int port = -1;

    /**
     * The specified file name on that host. {@code file} is
     * defined as {@code path[?query]}
     * @serial
     */
    private String file;

    /**
     * The query part of this URL.
     */
    private transient String query;

    /**
     * The authority part of this URL.
     * @serial
     */
    private String authority;

    /**
     * The path part of this URL.
     */
    private transient String path;
    /**
     * The userinfo part of this URL.
     */
    private transient String userInfo;

    /**
     * # reference.
     * @serial
     */
    private String ref;
    
    ...
}
代码转载自:
*****https://geek-docs.com/java/java-url/g_url-class-java-examples.html************



// Java program to demonstrate working of URL
  
// Importing required classes
import java.net.MalformedURLException;
import java.net.URL;
  
// Main class
// URL class
public class GFG {
  
    // Main driver method
    public static void main(String[] args)
        throws MalformedURLException
    {
  
        // Creating a URL with string representation
        URL url1 = new URL(
            "https://www.google.co.in/?gfe_rd=cr&ei=ptYq"
            + "WK26I4fT8gfth6CACg#q=geeks+for+geeks+java");
  
        // Creating a URL with a protocol,hostname,and path
        URL url2 = new URL("http", "www.geeksforgeeks.org",
                           "/jvm-works-jvm-architecture/");
  
        URL url3 = new URL(
            "https://www.google.co.in/search?"
            + "q=gnu&rlz=1C1CHZL_enIN71"
            + "4IN715&oq=gnu&aqs=chrome..69i57j6"
            + "9i60l5.653j0j7&sourceid=chrome&ie=UTF"
            + "-8#q=geeks+for+geeks+java");
  
        // Printing the string representation of the URL
        System.out.println(url1.toString());
        System.out.println(url2.toString());
        System.out.println();
        System.out.println(
            "Different components of the URL3-");
  
        // Retrieving the protocol for the URL
        System.out.println("Protocol:- "
                           + url3.getProtocol());
  
        // Retrieving the hostname of the url
        System.out.println("Hostname:- " + url3.getHost());
  
        // Retrieving the default port
        System.out.println("Default port:- "
                           + url3.getDefaultPort());
  
        // Retrieving the query part of URL
        System.out.println("Query:- " + url3.getQuery());
  
        // Retrieving the path of URL
        System.out.println("Path:- " + url3.getPath());
  
        // Retrieving the file name
        System.out.println("File:- " + url3.getFile());
  
        // Retrieving the reference
        System.out.println("Reference:- " + url3.getRef());
    }
}

运行结果:
    https://www.google.co.in/?gfe_rd=cr&ei=ptYqWK26I4fT8gfth6CACg#q=geeks+for+geeks+java
    https://www.geeksforgeeks.org/jvm-works-jvm-architecture/

    Different components of the URL3-
    Protocol:- https
    Hostname:- www.google.co.in
    Default port:- 443
    Query:- q=gnu&rlz=1C1CHZL_enIN714IN715&oq=gnu&aqs=chrome..69i57j69i60l5.653j0j7&sourceid=chrome&ie=UTF-8
    Path:- /search
    File:- /search?q=gnu&rlz=1C1CHZL_enIN714IN715&oq=gnu&aqs=chrome..69i57j69i60l5.653j0j7&sourceid=chrome&ie=UTF-8
    Reference:- q=geeks+for+geeks+java

ClassLoader

  • java 类加载过程(暂时挖个坑,后面填

到了这里,关于Reflection java反射源码分析的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • .net反射(Reflection)

    .NET 反射(Reflection)是指在运行时动态地检查、访问和修改程序集中的类型、成员和对象的能力。通过反射,你可以在运行时获取类型的信息、调用方法、访问字段和属性,以及创建对象实例,而无需在编译时知道这些类型的具体信息。 换句话说,反射可以在类的内部成员不

    2024年04月25日
    浏览(28)
  • 【.NET Core】反射(Reflection)详解(三)

    反射提供了对已封装的程序集、模型和类型的对象一种动态访问方法。反射包含动态加载程序集的Assembly类、程序集中模块访问的Module类、对类信息Type类、构造函数信息ConstructorInfo类、方法信息MethodInfo类、字段信息FieldInfo类、事件信息EventInfo类、属性信息PropertyInfo类、参数信

    2024年02月03日
    浏览(22)
  • [Unity/URP学习]反射探针(Reflection Probe)

    传统上,游戏使用一种称为_反射贴图_的技术来模拟来自对象的反射,同时将处理开销保持在可接受的水平。此技术假定场景中的所有反射对象都可以“看到”(因此会反射)完全相同的周围环境。如果游戏的主角(比如闪亮的汽车)处于开放空间中,此技术将非常有效,但

    2023年04月09日
    浏览(29)
  • C#中的反射(Reflection)使用经典案例

    C#中的反射(Reflection)是.NET框架提供的一种强大的运行时元编程机制,它允许程序在运行时获取类型信息、创建对象实例、调用方法、访问字段和属性等,而这些操作在编译时可能是未知的。以下是几个使用反射的典型场景: 1. 动态加载和调用类的方法 假设有一个库包含多

    2024年02月02日
    浏览(33)
  • unity在使用Reflection Probe(反射探头)bake(烘焙)时,无法反射出范围內的物体。

    bake后发现反射探头还是原来的样子,解决办法以下: 打开lighting设置,观察最下面是否为图中这样   如果是,则点击旁边的cancel即可解决问题。     

    2024年02月12日
    浏览(28)
  • 【Mybatis源码分析】Mybatis中的反射(MetaObject)详细讲解

    在使用Mybatis,编写DQL语句时,查询结果可能会是多个,多变量指定肯定是不现实的。而Mybatis可以进行映射,将JDBC返回的结果映射到实例类或者Map对象中,方便开发者直接使用返回对象,就可以得到从数据库取出来的结果。 映射原理大伙都知道是利用了反射(因为咱就只是通

    2023年04月08日
    浏览(63)
  • Java反射源码学习之旅

    前段时间组内针对“拷贝实例属性是应该用BeanUtils.copyProperties()还是MapStruct”这个问题进行了一次激烈的battle。支持MapStruct的同学给出了他嫌弃BeanUtils的理由:因为用了反射,所以慢。 这个理由一下子拉回了我遥远的记忆,在我刚开始了解反射这个Java特性的时候,几乎看

    2024年02月11日
    浏览(41)
  • Java反射源码学习之旅 | 京东云技术团队

    前段时间组内针对“拷贝实例属性是应该用BeanUtils.copyProperties()还是MapStruct”这个问题进行了一次激烈的battle。支持MapStruct的同学给出了他嫌弃BeanUtils的理由:因为用了反射,所以慢。 这个理由一下子拉回了我遥远的记忆,在我刚开始了解反射这个Java特性的时候,几乎看

    2024年02月12日
    浏览(29)
  • Java反射机制,动态代理,hook以及在Retrofit源码中的应用

    1.反射的基础知识: Java的反射机制是指在程序的运行状态中,可以构造任意一个类的对象,可以了解任意一个对象所属的类,可以了解任意一个类的成员变量和方法,可以调用任意一个对象的属性和方法。这种动态获取程序信息以及动态调用对象的功能称为Java语言的反射机

    2024年02月13日
    浏览(31)
  • Java集合框架之ArrayList源码分析

    ArrayList是Java提供的线性集合,本篇笔记将从源码(java SE 17)的角度学习ArrayList: 什么是ArrayList? ArrayList底层数据结构是怎么实现的? 作为一个容器,分析增删改查的过程 ArrayList的扩容机制 由ArrayList的定义可知,ArrayList继承了AbstractList抽象类,实现了List、RandomAccess、Cloneabl

    2024年02月07日
    浏览(46)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包