Reflection java反射源码分析

news/2024/12/2 15:49:36/

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类源码分析

    //泛型类
    public final class Class<T> implements java.io.Serializable,GenericDeclaration,Type,AnnotatedElement {//重要方法//获取Class对象 static修饰@CallerSensitivepublic 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 属性@CallerSensitivepublic Field getField(String name){...}//获取所有public属性,返回属性数组@CallerSensitivepublic 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@CallerSensitivepublic Field[] getDeclaredFields() throws SecurityException {...}//Returns a Field object that reflects the specified declared field of the class or interface represented by this Class object.@CallerSensitivepublic Field getDeclaredField(String name)throws NoSuchFieldException, SecurityException {...}//2.获取方法//(1).getMethod  name为方法名,因为重载的缘故根据后面的可变长参数来指定特定的方法@CallerSensitivepublic Method getMethod(String name, Class<?>... parameterTypes)throws NoSuchMethodException, SecurityException {...}//(2).getMethods()@CallerSensitivepublic Method[] getMethods() throws SecurityException {...}//(3)getDeclaredMethods()@CallerSensitivepublic Method[] getDeclaredMethods() throws SecurityException {。。。}//(4).getDeclaredMethod()@CallerSensitivepublic Method getDeclaredMethod(String name, Class<?>... parameterTypes)throws NoSuchMethodException, SecurityException {...}//3.获取构造函数@CallerSensitivepublic Constructor<T> getConstructor(Class<?>... parameterTypes)throws NoSuchMethodException, SecurityException{}@CallerSensitivepublic Constructor<?>[] getConstructors() throws SecurityException {}@CallerSensitivepublic Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)throws NoSuchMethodException, SecurityException{...}@CallerSensitivepublic 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.获取类中定义的类和嵌套接口@CallerSensitivepublic Class<?>[] getClasses() {...}@CallerSensitivepublic 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 optimizationpublic 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.@CallerSensitivepublic URL getResource(String name) {...}@CallerSensitivepublic 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 methodpublic static void main(String[] args)throws MalformedURLException{// Creating a URL with string representationURL 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 pathURL 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 URLSystem.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 URLSystem.out.println("Protocol:- "+ url3.getProtocol());// Retrieving the hostname of the urlSystem.out.println("Hostname:- " + url3.getHost());// Retrieving the default portSystem.out.println("Default port:- "+ url3.getDefaultPort());// Retrieving the query part of URLSystem.out.println("Query:- " + url3.getQuery());// Retrieving the path of URLSystem.out.println("Path:- " + url3.getPath());// Retrieving the file nameSystem.out.println("File:- " + url3.getFile());// Retrieving the referenceSystem.out.println("Reference:- " + url3.getRef());}
}运行结果:https://www.google.co.in/?gfe_rd=cr&ei=ptYqWK26I4fT8gfth6CACg#q=geeks+for+geeks+javahttps://www.geeksforgeeks.org/jvm-works-jvm-architecture/Different components of the URL3-Protocol:- httpsHostname:- www.google.co.inDefault port:- 443Query:- q=gnu&rlz=1C1CHZL_enIN714IN715&oq=gnu&aqs=chrome..69i57j69i60l5.653j0j7&sourceid=chrome&ie=UTF-8Path:- /searchFile:- /search?q=gnu&rlz=1C1CHZL_enIN714IN715&oq=gnu&aqs=chrome..69i57j69i60l5.653j0j7&sourceid=chrome&ie=UTF-8Reference:- q=geeks+for+geeks+java

ClassLoader

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

http://www.ppmy.cn/news/58314.html

相关文章

01背包问题个人剖析

背包问题 文章目录 背包问题1 01背包问题1.1 问题阐述1.2 问题分析 背包问题中我最初的一些疑惑 1 01背包问题 我参考了文献背包九讲。https://github.com/tianyicui/pack/raw/master/V2.pdf 背包九讲的作者是ACM大牛崔天翼。 1.1 问题阐述 有 N N N件物品和一个容量为 V V …

小红书违禁词有哪些,小红书违禁词汇总分享

大家都知道小红书平台对于违禁词的管控一向非常严格&#xff0c;笔记中一旦出现就可能被限流&#xff0c;今天为大家整理了一份小红书违禁词汇总&#xff0c;希望能够帮助大家避免被限流。 小红书违禁词汇总大致有以下几个分类&#xff0c;大家平时写笔记的时候最好避开这些词或…

辅助驾驶功能开发-功能规范篇(16)-2-领航辅助系统NAP-功能ODD定义

1.系统定义 智能驾驶系统包含行车场景功能和泊车场景功能,行车场景功能包括安全ADAS功能、基础ADAS功能和高阶ADAS功能三大类,本文档定义高阶ADAS功能中的导航辅助驾驶功能用例。 1.1.高阶ADAS功能列表 功能需求ID 功能分类 功能名称

网络安全入门基础知识

计算机网络 计算机网络是利用通信线路将不同地理位置、具有独立功能的计算机和通信设备连接起来&#xff0c;实现资环共享和信息传递等目的的计算机系统。 主要有局域网&#xff0c;城域网&#xff0c;广域网&#xff0c;和互联网等 信息系统 信息系统是能进行信息采集、传…

Qt常用快捷键

Qt常用快捷键 1.添加头文件&#xff1a;Alt Enter2.查看槽函数的实现 位置&#xff1a;F2 / F43.快速查看帮助文档&#xff1a;F14.代码快速对齐&#xff1a;Ctrl I5.代码全选&#xff1a;Ctrl A6.保存&#xff1a;Ctrl S7.代码复制&#xff1a;Ctrl C8.代码粘贴&#xff…

动态规划——最大子数组和

问题描述&#xff1a; 最大子数组和Time Limit: 1000 MSMemory Limit: 5000 KB Description 给定一个长度为N的int型数组a[0,1,2,...N-1], 请计算最大子数组和.Input 第一行输入M表示包含M组测试数据&#xff0c;每组先输入N (N<50000), 接着输入N个int型整数.Output 输…

CentOS+nginx手动搭建WordPress

文章目录 前提条件php安装安装 EPEL 源及源管理工具&#xff1a;安装 REMI 源&#xff1a;安装 PHP7.3 及扩展&#xff1a;设置开机自动启动其他php命令 wordpress 安装下载WordPress将下载的WordPress移动至网站根目录修改WordPress配置文件配置nginx 创建完成后根据域名访问 …

C++的智能指针

文章目录 1. 内存泄漏1.1 什么是内存泄漏1.2 内存泄漏分类 2. 为什么需要智能指针3. 智能指针的使用及原理3.1 RAII3.2 使用RAII思想设计的SmartPtr类3.3 让SmartPtr像指针一样3.3 SmartPtr的拷贝3.4 auto_ptr3.5 unique_ptr3.6 shared_ptr3.6.1 shared_ptr的循环引用3.6.2 wea…