理解JAVA反射机制

摘抄:http://www.importnew.com/17616.html

Class反射机制

  • 指的是可以用于运行时加载、探知和使用编译期间完全未知的类。
  • 程序在运行状态中,可以动态加载一个只有名称的类,对于任意一个已经加载的类,都能够知道这个类的所有属性和方法,对于任意一个对象,都能调用他的任意一个方法和属性。
  • 加载完类之后,在堆内存中会产生一个Class类型的对象(一个类只有一个Class对象),这个对象包含了完整的类的结构信息,而且这个Class对象就像一面镜子,透过这个镜子看到类的结构,所以被称之为:反射。

Instances of the class Class represent classes and interfaces in a running Java application. An enum is a kind of class and an annotation is a kind of interface. Every array also belongs to a class that is reflected as a Class object that is shared by all arrays with the same element type and number of dimensions(维度). The primitive Java types (boolean, byte, char, short, int, long, float, anddouble), and the keyword void are also represented as Class objects.

  • 每个类被加载进入内存之后,系统就会为该类生成一个对应的java.lang.Class对象,通过该Class对象就可以访问到JVM中的这个类。

Class对象的获取

  • 对象的getClass()方法;
  • 类的.class(最安全/性能最好)属性;
  • 运用Class.forName(String className)动态加载类,className需要是类的全限定名(最常用)。
posted @ 2017-10-25 17:36  穿越亚平宁的盛夏  阅读(145)  评论(0编辑  收藏  举报