Java Basics (reflection)

Reflecting frame design is the soul

Premise used: Class must be obtained on behalf of bytecode, Class class is used to represent the .class files (bytecodes)

For more details, visit: https://blog.csdn.net/sinat_38259539/article/details/71799078

I. Overview

JAVA reflection in the operating state , for any of a class, are made known to all properties and methods of this class; for any object, are able to call any of its methods and properties; this information acquired dynamically and dynamic invocation a method of object function called reflection mechanism java language.
To Anatomy of a class, you must first get to the bytecode file object class. Class is the method used by the anatomy class. Class acquired so first object type corresponding to each byte code file. [Overview] reflection

Briefly : reflecting the java class is mapped to the various components of a java object

For example: a category are: fields, methods, construction methods, package information, etc., may be performed using the reflection technique anatomy class, the components of each mapped into one object.

(In fact: a member of a class of these methods, constructor, there is described a class to class added)

   FIG class loading process is normal: with the principles reflected in the class object. Familiarize yourself with loads of time: the origin of the Class object of the class file is read into memory, and whom to create a Class object.

The Class object which is very special. We first look at the Class class

Second, view the Class class api Detailed (1.7 API) in java

 


   Class Instance of the class represent classes and interfaces Java applications running in. Jvm i.e. there are N number of instances of each class that has a Class object. (Including basic data types)

   Class 没有公共构造方法。Class 对象是在加载类时由 Java 虚拟机以及通过调用类加载器中的defineClass 方法自动构造的。也就是这不需要我们自己去处理创建,JVM已经帮我们创建好了。

  三、反射的使用(这里使用Student类做演示)

先写一个Student类。

1、获取Class对象的三种方式

1.1 Object ——> getClass();
1.2 任何数据类型(包括基本数据类型)都有一个“静态”的class属性
1.3 通过Class类的静态方法:forName(String  className)(常用)

因为所有类都继承Object类。从而调用Object类来获取

注意:在运行期间,一个类,只有一个Class对象产生。

     三种方式常用第三种,第一种对象都有了还要反射干什么。第二种需要导入类的包,依赖太强,不导包就抛编译错误。一般都第三种,一个字符串可以传入也可写在配置文件中等多种方法。

2、通过反射获取构造方法并使用:

3、获取成员变量并调用:

4、获取成员方法并调用:

5、反射main方法:

6.反射方法的其它使用之---通过反射运行配置文件内容:

7.反射方法的其它使用之---通过反射越过泛型检查

泛型用在编译期,编译过后泛型擦除(消失掉)。所以是可以通过反射越过泛型检查

 

发布了100 篇原创文章 · 获赞 47 · 访问量 21万+

Guess you like

Origin blog.csdn.net/sl1990129/article/details/103179290