国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Reflection java反射源碼分析

這篇具有很好參考價值的文章主要介紹了Reflection java反射源碼分析。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

Reflection 源碼分析

定義

Java的反射(reflection)機制是指在程序的運行狀態(tài)中,可以構(gòu)造任意一個類的對象,可以了解任意一個對象所屬的類,可以了解任意一個類的成員變量和方法,可以調(diào)用任意一個對象的屬性和方法。這種動態(tài)獲取程序信息以及動態(tài)調(diào)用對象的功能稱為Java語言的反射機制。反射被視為動態(tài)語言的關鍵

Class對象

  • Class對象是JVM生成用來保存對象的類的信息的。Java程序執(zhí)行之前需要經(jīng)過編譯、加載、鏈接和初始化這幾個階段,編譯階段會將源碼文件編譯為.class字節(jié)碼文件,編譯器同時會在.class文件中生成Class對象,加載階段通過JVM內(nèi)部的類加載機制,將Class對象加載到內(nèi)存中。在創(chuàng)建對象實例之前,JVM會先檢查Class對象是否在內(nèi)存中存在,如果不存在,則加載Class對象,然后再創(chuàng)建對象實例,如果存在,則直接根據(jù)Class對象創(chuàng)建對象實例。JVM中只有一個Class對象,但可以根據(jù)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);
          }
      }
      
      結(jié)果:
          class org.yrdm.ch1.Cat
      
      1. 調(diào)用類實例對象的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);
          }
      }
      
      結(jié)果:
          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);
          }
      }
      
      結(jié)果:
          class org.yrdm.ch1.Cat
      
  • Class類源碼分析文章來源地址http://www.zghlxwxcb.cn/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);
        }
                                      
        //創(chuàng)建實例,直接調(diào)用無參構(gòu)造進行構(gòu)造 jdk9后被棄用,使用class.getDeclaredConstructor().newInstance()代替
        @CallerSensitive
        @Deprecated(since="9")
        public T newInstance()
            throws InstantiationException, IllegalAccessException
        {...}
        
        //每個結(jié)構(gòu)都有這四件套 getXXX()  getXXXs()  getDealaredXXX()  getDeclaredXXXs()
        //1.屬性
        //根據(jù)參數(shù)獲取屬性 public 屬性
        @CallerSensitive
        public Field getField(String name){...}
        
        //獲取所有public屬性,返回屬性數(shù)組
        @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為方法名,因為重載的緣故根據(jù)后面的可變長參數(shù)來指定特定的方法
        @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.獲取構(gòu)造函數(shù)
         @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.獲取所實現(xiàn)的接口
        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;
    
    ...
}
代碼轉(zhuǎn)載自:
*****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());
    }
}

運行結(jié)果:
    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反射源碼分析的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權(quán),不承擔相關法律責任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領支付寶紅包贊助服務器費用

相關文章

  • .net反射(Reflection)

    .net反射(Reflection)

    .NET 反射(Reflection)是指在運行時動態(tài)地檢查、訪問和修改程序集中的類型、成員和對象的能力。通過反射,你可以在運行時獲取類型的信息、調(diào)用方法、訪問字段和屬性,以及創(chuàng)建對象實例,而無需在編譯時知道這些類型的具體信息。 換句話說,反射可以在類的內(nèi)部成員不

    2024年04月25日
    瀏覽(22)
  • 【.NET Core】反射(Reflection)詳解(三)

    反射提供了對已封裝的程序集、模型和類型的對象一種動態(tài)訪問方法。反射包含動態(tài)加載程序集的Assembly類、程序集中模塊訪問的Module類、對類信息Type類、構(gòu)造函數(shù)信息ConstructorInfo類、方法信息MethodInfo類、字段信息FieldInfo類、事件信息EventInfo類、屬性信息PropertyInfo類、參數(shù)信

    2024年02月03日
    瀏覽(54)
  • [Unity/URP學習]反射探針(Reflection Probe)

    [Unity/URP學習]反射探針(Reflection Probe)

    傳統(tǒng)上,游戲使用一種稱為_反射貼圖_的技術(shù)來模擬來自對象的反射,同時將處理開銷保持在可接受的水平。此技術(shù)假定場景中的所有反射對象都可以“看到”(因此會反射)完全相同的周圍環(huán)境。如果游戲的主角(比如閃亮的汽車)處于開放空間中,此技術(shù)將非常有效,但

    2023年04月09日
    瀏覽(29)
  • C#中的反射(Reflection)使用經(jīng)典案例

    C#中的反射(Reflection)使用經(jīng)典案例

    C#中的反射(Reflection)是.NET框架提供的一種強大的運行時元編程機制,它允許程序在運行時獲取類型信息、創(chuàng)建對象實例、調(diào)用方法、訪問字段和屬性等,而這些操作在編譯時可能是未知的。以下是幾個使用反射的典型場景: 1. 動態(tài)加載和調(diào)用類的方法 假設有一個庫包含多

    2024年02月02日
    瀏覽(17)
  • unity在使用Reflection Probe(反射探頭)bake(烘焙)時,無法反射出范圍內(nèi)的物體。

    unity在使用Reflection Probe(反射探頭)bake(烘焙)時,無法反射出范圍內(nèi)的物體。

    bake后發(fā)現(xiàn)反射探頭還是原來的樣子,解決辦法以下: 打開lighting設置,觀察最下面是否為圖中這樣 ? 如果是,則點擊旁邊的cancel即可解決問題。? ? ?

    2024年02月12日
    瀏覽(17)
  • 【Mybatis源碼分析】Mybatis中的反射(MetaObject)詳細講解

    【Mybatis源碼分析】Mybatis中的反射(MetaObject)詳細講解

    在使用Mybatis,編寫DQL語句時,查詢結(jié)果可能會是多個,多變量指定肯定是不現(xiàn)實的。而Mybatis可以進行映射,將JDBC返回的結(jié)果映射到實例類或者Map對象中,方便開發(fā)者直接使用返回對象,就可以得到從數(shù)據(jù)庫取出來的結(jié)果。 映射原理大伙都知道是利用了反射(因為咱就只是通

    2023年04月08日
    瀏覽(20)
  • Java反射源碼學習之旅

    Java反射源碼學習之旅

    前段時間組內(nèi)針對“拷貝實例屬性是應該用BeanUtils.copyProperties()還是MapStruct”這個問題進行了一次激烈的battle。支持MapStruct的同學給出了他嫌棄BeanUtils的理由:因為用了反射,所以慢。 這個理由一下子拉回了我遙遠的記憶,在我剛開始了解反射這個Java特性的時候,幾乎看

    2024年02月11日
    瀏覽(19)
  • Java反射源碼學習之旅 | 京東云技術(shù)團隊

    Java反射源碼學習之旅 | 京東云技術(shù)團隊

    前段時間組內(nèi)針對“拷貝實例屬性是應該用BeanUtils.copyProperties()還是MapStruct”這個問題進行了一次激烈的battle。支持MapStruct的同學給出了他嫌棄BeanUtils的理由:因為用了反射,所以慢。 這個理由一下子拉回了我遙遠的記憶,在我剛開始了解反射這個Java特性的時候,幾乎看

    2024年02月12日
    瀏覽(20)
  • Java反射機制,動態(tài)代理,hook以及在Retrofit源碼中的應用

    Java反射機制,動態(tài)代理,hook以及在Retrofit源碼中的應用

    1.反射的基礎知識: Java的反射機制是指在程序的運行狀態(tài)中,可以構(gòu)造任意一個類的對象,可以了解任意一個對象所屬的類,可以了解任意一個類的成員變量和方法,可以調(diào)用任意一個對象的屬性和方法。這種動態(tài)獲取程序信息以及動態(tài)調(diào)用對象的功能稱為Java語言的反射機

    2024年02月13日
    瀏覽(17)
  • Java集合框架之ArrayList源碼分析

    ArrayList是Java提供的線性集合,本篇筆記將從源碼(java SE 17)的角度學習ArrayList: 什么是ArrayList? ArrayList底層數(shù)據(jù)結(jié)構(gòu)是怎么實現(xiàn)的? 作為一個容器,分析增刪改查的過程 ArrayList的擴容機制 由ArrayList的定義可知,ArrayList繼承了AbstractList抽象類,實現(xiàn)了List、RandomAccess、Cloneabl

    2024年02月07日
    瀏覽(22)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領取紅包,優(yōu)惠每天領

二維碼1

領取紅包

二維碼2

領紅包